1

I need to access axios header authorization token in server side(Node), showing undefined. Please help..

Client side(React) request:

var config = {
        headers: {
            'cache-control':'no-cache',
            'content-type': 'application/x-www-form-urlencoded',
            'authorization' :'bearer '+Auth.getToken()
          }
      };
    axios.get(ApiConfig.API_BASE+'api/admin/profile/', config).then(function(response) {
      this.setState({status:'success', profile: response.data.data});
    }).catch(function(response) {
        console.log(response);
    });

Server side(Node):

module.exports = (req, res, next) => {

console.log(req.headers.authorization); 

  if(!req.headers.authorization) {
    return res.status(401).end();
  }
 }; 

Log showing undefined. I also console the entire header, but their output is:

{ host: 'localhost:8027',
  'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:55.0) Gecko/20100101 Firefox/55.0',
  accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  'accept-language': 'en-US,en;q=0.5',
  'accept-encoding': 'gzip, deflate',
  'access-control-request-method': 'GET',
  'access-control-request-headers': 'authorization,cache-control',
  origin: 'http://localhost:3001',
  connection: 'keep-alive' }

How do I retrieve the authorization token value?

Thank you.

Diptesh Atha
  • 851
  • 8
  • 18
  • Possible duplicate of [How to extract request http headers from a request using NodeJS connect](https://stackoverflow.com/questions/13147693/how-to-extract-request-http-headers-from-a-request-using-nodejs-connect) – Hemerson Carlin Sep 25 '17 at 15:12

2 Answers2

0

I'm assuming you are using express. If so, instead of getting the header value as req.headers.authorization, try req.get('authorization').

http://expressjs.com/en/api.html#req.get

Hemerson Carlin
  • 7,354
  • 1
  • 27
  • 38
-1

If you are making a cross-origin HTTP request, please make sure CORS has been enabled in your server. If you are using express cors middleware can be used.

I guess your problem here is that since CORS has not been enabled, your server will receive a OPTIONS request first, so the entire header you console is from the OPTIONS request not the GET request as you desired. You can use console.log(req.method) to verify. BTW req.headers.authorization is ok to receive the header.

movier
  • 1
  • 3
  • console.log(req.method); showing "OPTIONS" and req.headers.authorization still undefined. – Diptesh Atha Sep 26 '17 at 10:25
  • Have you enabled CORS on your server? – movier Sep 26 '17 at 10:30
  • Yes, this is my localhost. And I set app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization"); res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS'); next(); }); – Diptesh Atha Sep 26 '17 at 10:36