Search code examples
node.jsangulartoken

Headers in Angular HTTP Request to NodeJS API


I can't send the headers in my HTTPs requests using my Angular app. I have to send a Token to authorize the request in my back-end that is a NodeJS API. Each route is checked.

When I print the request headers:

host: 'localhost:21124',
connection: 'keep-alive',
'access-control-request-method': 'GET',
origin: 'http://localhost:4200',
'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.89 Safari/537.36',
'access-control-request-headers': 'authorization,content-type',
accept: '*/*',
'accept-encoding': 'gzip, deflate, br',
'accept-language': 'pt,en-US;q=0.9,en;q=0.8' }

I use the "Authorization" control header to send my Token.
Here is my CORS and the valitation (API):

app.use(helmet());
app.use(function (req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
    res.setHeader('Access-Control-Allow-Credentials', true);
    next();
});
app.use(function (req, res, next) {
    if (req.url !== '/login') {
        var token = req.headers['Authorization'];
        if (!token) {
            res.status(401).send('Token não provido!')
        } else {
            jwt.verify(token, SECRET, function(err, decoded) {
            if (err) {
                res.status(500).send('Token inválido!');
            } else if (decoded) {
                var date = new Date();
            if (decoded.exp < date.getTime()) {
                next();
            } else {
                res.status(500).send('Token inválido!');
            }
          }
        });
      }
    } else {
        next();
    }
});

Here is my Angular API Service where I do the requests (one request for example):

getAssociados(idClube: string): any {
   const token = localStorage.getItem('token');
   const headers = new Headers({ 'Content-Type': 'application/json', 'Authorization': token });
   const options = new RequestOptions({ headers: headers });
   return this.http.get(this.associadoUrl + idClube, options)
      .map(res => res.json());

}

I already used Postman to do the resquests. Everything fine. I got the error just in my Angular app (No authorized).


Solution

  • According to discussion of cross-origin, if you send

    Access-Control-Allow-Origin: *
    

    then no authorization information is ever sent. You will need to change your node.js app to send an access-control-allow-origin header that explicitly mentions the origin header you get.

    In addition, note that the options preflight request will not include the authorization header; that is only sent after the browser validates the cross-origin request.