$http request headers not being set correctly

Loading

If your $http request headers in AngularJS are not being set correctly, this can lead to issues like:

  • Authentication failures (e.g., missing token),
  • CORS preflight errors,
  • Content not being recognized by the backend (wrong Content-Type),
  • Unexpected response errors.

Let’s walk through how to set headers properly in $http, what causes headers not to be applied, and step-by-step fixes.


1. Correct Syntax for Setting Headers in $http

Here’s how to correctly include headers in a $http request:

$http({
method: 'POST',
url: '/api/data',
data: { key: 'value' },
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer your_token_here'
}
});

Alternatively:

$http.post('/api/data', { key: 'value' }, {
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer your_token_here'
}
});

2. Why Headers May Not Be Set Properly

A. You Forgot to Pass the headers Object

Wrong:

$http.post('/api/data', { key: 'value' }); // No headers set

Fix:

$http.post('/api/data', { key: 'value' }, {
headers: { 'Content-Type': 'application/json' }
});

B. Wrong Header Name

Header names must be correct. They are case-insensitive, but consistency matters.

Examples of valid headers:

  • Content-Type
  • Authorization
  • Accept

Fix:

Double-check spelling and case.


C. Header Being Overwritten by Interceptor or Defaults

If you’re using $httpProvider.defaults.headers or an interceptor, it may override your manually set headers.

Fix:

Check your configuration:

$httpProvider.defaults.headers.common['Authorization'] = 'Bearer xyz';

Or check interceptors:

.factory('authInterceptor', function($q) {
return {
request: function(config) {
config.headers = config.headers || {};
config.headers.Authorization = 'Bearer token';
return config;
}
};
});

D. Using transformRequest Improperly

Overriding transformRequest might strip out your headers if not handled carefully.

Fix:

Only modify data, not headers, in transformRequest.

Correct example:

$http({
method: 'POST',
url: '/api/data',
data: { key: 'value' },
transformRequest: [function(data) {
return angular.toJson(data);
}],
headers: {
'Content-Type': 'application/json'
}
});

E. CORS and Browser Restrictions

If you’re making a cross-origin request, and the server doesn’t allow specific headers via CORS, the browser may block or ignore them.

Fix:

  • Check browser’s Network > Request Headers.
  • Check if your header is in the Access-Control-Allow-Headers response from the server.

Example CORS response headers:

Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: Content-Type, Authorization

If your custom header (e.g., X-Custom-Token) is not allowed, the browser will block it.


F. Using jQuery or Fetch Instead of $http

AngularJS $http won’t intercept or add headers to $.ajax() or fetch() requests.

Fix: Ensure you’re using AngularJS’s $http.


3. Debugging Header Issues – Step by Step

Step 1: Add Logging

$http.post('/api/data', { key: 'value' }, {
headers: {
'Authorization': 'Bearer xyz'
}
}).then(function(response) {
console.log('Success', response);
}, function(error) {
console.error('Error', error);
});

Step 2: Use Browser DevTools

  • Open Network tab
  • Click on the failed request
  • Go to Request Headers
  • Check if your headers are present

Step 3: Check Server Logs

Sometimes the issue is on the server, not AngularJS. Confirm what headers are received server-side.


4. Setting Global Headers

If you need to apply headers to all requests:

app.config(function($httpProvider) {
$httpProvider.defaults.headers.common['Authorization'] = 'Bearer xyz';
});

Or dynamically in an interceptor:

app.factory('authInterceptor', function($q, AuthService) {
return {
request: function(config) {
const token = AuthService.getToken();
if (token) {
config.headers = config.headers || {};
config.headers.Authorization = 'Bearer ' + token;
}
return config;
}
};
});

app.config(function($httpProvider) {
$httpProvider.interceptors.push('authInterceptor');
});

5. Common Fix Scenarios

Want to send JSON with Auth Token:

$http.post('/api/data', { name: 'test' }, {
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer xyz'
}
});

✔ Want to override Content-Type globally:

app.config(function($httpProvider) {
$httpProvider.defaults.headers.post['Content-Type'] = 'application/json';
});

Leave a Reply

Your email address will not be published. Required fields are marked *