1

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>

1 Answer 1

2

I have found answer myself.

Its not related to angular or .htaccess thing. Its more related to the server side.

When CORS request is made, the browser makes a test(preflight) request to see if everything is ok, then only it makes actual request.

Following code in the API call solved the problem.

<?php

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Headers: X-Requested-With, Authorization');
    exit;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.