1
votes

I don't understand why express js cannot read my header.

I use vuejs + axios for send data. I use a module for intercept request ans response for send token.

In axios module :

axios.interceptors.request.use((req) => {
  req.headers.authorization = `Bearer: ${MYTOKEN}`;
  return req;
});

In my server, i use nodesJS + Express with middleware :

const router = express.Router();

router.use(function timeLog(req, res, next) {
    console.log(req.headers.authorization); // undefined :(
})

So req.headers do not contains key 'authorization' and console.log(req.headers.authorization); return to me 'UNDEFINED'.

I've try to put req.header.BLABLABLA. I find it but not as key. I really don't understand.

Exemple of return with authorization :

{ host: 'localhost:5000',
  connection: 'keep-alive',
  'access-control-request-method': 'POST',
  origin: 'http://localhost:8080',
  'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36',
  'access-control-request-headers': 'authorization,content-type',
  accept: '*/*',
  'accept-encoding': 'gzip, deflate, br',
  'accept-language': 'fr-FR,fr;q=0.9,en;q=0.8,en-US;q=0.7,ru;q=0.6' 
}
1
PS : When i use postman and add a header. I can get header in my nodeJS console. I think the problem come from axios.Brice Chaponneau

1 Answers

-1
votes

You're using Axios in the wrong way.

You're trying to log headers of the Express Request, not headers of the Axios.

// server/index.js

router.use(function timeLog(req, res, next) {
    console.log(req.headers.authorization); // of course this is will undefined
})

If you're doing like so, you'll get your authorization headers...

// server/index.js

import axios from 'axios'

axios.interceptors.request.use((req) => {
    // `req` here, it's axios config, not express `req'.
    req.headers.authorization = `Bearer: ${MYTOKEN}`;
    return req;
});

router.use(function timeLog(req, res, next) {
    console.log(axios.headers.authorization); // here we are
})