CodexBloom - Programming Q&A Platform

AngularJS 1.8: Issue with $http Interceptor Not Modifying Request Headers as Expected

đź‘€ Views: 137 đź’¬ Answers: 1 đź“… Created: 2025-09-06
angularjs http interceptor JavaScript

I recently switched to I'm updating my dependencies and I'm working on a project and hit a roadblock... Quick question that's been bugging me - I'm currently trying to implement an $http interceptor in my AngularJS 1.8 application to append an authorization token to every outgoing request. However, despite setting up the interceptor, it seems that the headers are not being modified as expected, and I'm still receiving a 401 Unauthorized error from the server. Here’s how I set up my interceptor: ```javascript angular.module('myApp').factory('authInterceptor', function() { return { request: function(config) { const token = localStorage.getItem('authToken'); if (token) { config.headers['Authorization'] = 'Bearer ' + token; } return config; } }; }); angular.module('myApp').config(function($httpProvider) { $httpProvider.interceptors.push('authInterceptor'); }); ``` I've double-checked that the token is indeed being stored correctly in localStorage and I'm able to retrieve it. I also tried adding some console logs within the interceptor to see if it’s being called: ```javascript request: function(config) { console.log('Intercepting request:', config); const token = localStorage.getItem('authToken'); if (token) { console.log('Token found:', token); config.headers['Authorization'] = 'Bearer ' + token; } else { console.log('No token found'); } return config; } ``` When I initiate a request, I see the interceptor log output, but the headers don’t seem to reflect the changes as expected when I inspect the network request in the browser’s Developer Tools. The actual request headers appear to be missing the `Authorization` header altogether. Additionally, I’ve tried wrapping my HTTP calls in a `$timeout` to ensure that my interceptor is applied, but that didn’t help either. I’m uncertain if this could be a scope issue or something related to the order of request handling. Any insights on what might be going wrong here or how to debug this further would be greatly appreciated! For context: I'm using Javascript on macOS. What am I doing wrong? I'd love to hear your thoughts on this.