I have following code
angular.module('myApp.Utils',[])
.factory('AuthInterceptor', function($q, $location) {
return {
request: function(config) {
config.headers = config.headers || {};
if (window.localStorage.token) {
config.headers.Authorization = 'Bearer ' + window.localStorage.token;
}
config.headers["Content-Type"] = 'application/x-www-form-urlencoded';
return config || $q.when(config);
},
response: function(response) {
if (response.status === 401) {
//redirect user to login page
$location.url('/login');
}
return response || $q.when(response);
}
};
})
.config(function($httpProvider) {
$httpProvider.interceptors.push('AuthInterceptor');
});
If we have value for token key in localStorage, it adds Authorization Header to every ajax calls made.
Problem
It works well if there is no token (No header sent). But when token exist in localstorage and I make an API call, I get following error
Response for preflight has invalid HTTP status code 404
After research i found that, the browser makes preflight request (OPTIONS request), before making a real request. I also found that we cannot send custom Headers in preflight request. So is there anyway to fix this, to send custom Headers only when making a real request.?
I have tried adding following in .htaccess of the server that serves API calls
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "Content-Type, Authorization, Origin, X-Requested-With"
Header always set Access-Control-Allow-Methods "GET,POST,HEAD,DELETE,PUT,OPTIONS"
</IfModule>