1

im trying to make an interceptor that appends an user token if exists on every request, the token exists but it doesnt send it... After the call is made I look at F12 ( Chrome Dev Tools) the call and the Authorization header is not there...

But if I debug it step by step I can see how in the config.headers.Authorization is there my token... but still not sending it throu the request... May I ask for some help please?

This is my interceptor

$httpProvider.interceptors.push(function($q, $location, $cookies){
    return {
        request: function(config){
            config.headers = config.headers || {};
            let token = $cookies.get('user');
            if (token) {
                config.headers.Authorization = 'Bearer ' + token;
            }
            return config;
        },
        response: function(response){
            return response;
        },
        responseError: function(response){
            if(response.status === 401 || response.status === 403){
                $location.path('/login')
            }
            return $q.reject(response);
        }
    }
  })

CORS config

var allowCrossDomain = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, DELETE, OPTIONS');
    res.header('Access-Control-Allow-Headers', 'X-Requested-With,Content-Type,Authorization');
    next();
}

Config before it be send

config before it be send

req/res preflight req/res preflight

4
  • Does your preflight options request return Access-Control-Allow-Headers: X-Requested-With,Content-Type,Authorization? Commented Jun 12, 2017 at 11:20
  • Yes It does, those are the allowed headers I've put on my server side Commented Jun 12, 2017 at 11:22
  • Could you try to console.log(config); directly above return config; is your configuration inside? It all seems fine to me right now. Commented Jun 12, 2017 at 11:36
  • Okay, I've just attached the picture to the OP, it seems all right to me too, im attaching the req/res on the preflight too Commented Jun 12, 2017 at 11:42

1 Answer 1

2

Ensure that your OPTIONS request does not need an "auth" and you will be fine. The W3 spec for CORS preflight requests says that user credentials should be excluded.

If HTTP-Status 401 has been returned by an OPTIONS request , a subrequest should not be send by the client. But it seems like there is a bug with some browsers. This browsers does send a subrequest even if the OPTIONS request returned 401.

In node.js you could check the request method by using req.method === 'OPTIONS'.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks you, this fixed my problem, i've justs added this if (req.method === "OPTIONS") res.sendStatus(200); else next();

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.