【问题标题】:ExpressJS + Axios : can't send header authorizationExpressJS + Axios:无法发送标头授权
【发布时间】:2018-12-28 22:00:43
【问题描述】:

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

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

在 axios 模块中:

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

在我的服务器中,我使用带中间件的nodesJS + Express:

const router = express.Router();

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

所以 req.headers 不包含密钥 'authorization' 和 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' 
}

【问题讨论】:

  • PS:当我使用邮递员并添加标题时。我可以在我的 nodeJS 控制台中获取标题。我认为问题来自 axios。

标签: express axios


【解决方案1】:

试试这个

axios.interceptors.request.use((req) => { // req 这里是 axios config,不表达 req'. req.headers.Authorization = Bearer: ${MYTOKEN}`; 返回请求; });

授权 => 以大写开头

【讨论】:

    【解决方案2】:

    您以错误的方式使用 Axios。

    您正在尝试记录 Express 请求的标头,而不是 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
    })
    

    【讨论】:

      猜你喜欢
      • 2020-05-22
      • 2017-11-23
      • 2017-10-29
      • 1970-01-01
      • 1970-01-01
      • 2019-04-11
      • 1970-01-01
      • 1970-01-01
      • 2019-05-31
      相关资源
      最近更新 更多