ExpressJS + Axios:无法发送标头授权

时间:2018-07-20 14:46:16

标签: express axios

我不明白为什么express js无法读取我的标头。

我使用vuejs + axios发送数据。 我使用一个模块来拦截发送令牌的请求和响应。

在axios模块中:

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

在我的服务器中,我将nodeJS + Express与中间件一起使用:

const router = express.Router();

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

因此req.headers不包含密钥“授权”和console.log(req.headers.authorization);返回我“未定义”。

我尝试放入req.header.BLABLABLA。我找到了,但不是关键。 我真的不明白。

授权退货示例:

{ 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 个答案:

答案 0 :(得分:0)

您使用Axios的方式错误。

您正在尝试记录Express Request的标头,而不是Axios的标头。

// server / index.js

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

如果您这样做,将会获得授权标头...

// 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
})