1

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).

5
  • When making the request in angular, is it sending the Authorization header? Also, can you confirm that token is not null. Commented Nov 8, 2017 at 14:30
  • Have you hosted your angular app? Commented Nov 8, 2017 at 14:30
  • @dzm I think Angular is not sending, but I added the Authorization to the header. Yes, the token is not null. Commented Nov 8, 2017 at 21:03
  • @Java Yes, I do. I build and deploy the Angular app as well the API. Same error. Commented Nov 8, 2017 at 21:04
  • Is it possible to post the specific changes you made to get it to work? Commented Mar 24, 2021 at 20:49

1 Answer 1

1

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.

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

4 Comments

Is it possible in localhost? I got the same error using localhost:4200. No Authorization field in header recived.
Error 01: OPTIONS http://localhost:21124/associado/5a030b4e9f90381a3d486204 401 (Unauthorized); Error 02: Failed to load http://localhost:21124/associado/5a030b4e9f90381a3d486204: Response for preflight has invalid HTTP status code 401
You need to get the preflight options request to return 200 with the right headers as discussed in the answer.
Solved. Thanks, but I have to do more changes: var token = req.headers['authorization'].replace(/"/g, ''); the Authorization must be in low case and I alse have to remove the quoute marks.

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.