简体   繁体   English

使用 Vue.JS 和 Node.JS 时未定义 Axios 授权标头

[英]Axios Authorization headers undefined when using Vue.JS and Node.JS

I got a problem when settings authorization headers to my axios instance.将授权标头设置到我的 axios 实例时出现问题。

Here is the code in my Vue.JS app running on http://localhost:8080 :这是我在http://localhost:8080上运行的 Vue.JS 应用程序中的代码:

axios.defaults.headers.common['Authorization'] = 'Bearer ' + token

axios.get(`/users/email/${myemail}`).then(response => {
   var user = response.data.result[0]
   ...
});

And here is a sample of my Node.JS server code running on http://localhost:3000 :这是我在http://localhost:3000上运行的 Node.JS 服务器代码示例:

// Add headers
app.use((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, Accept, X-Access-Token, X-Key, Authorization');

  res.setHeader('Access-Control-Allow-Credentials', true);

  next();
});

And :和 :

app.use((req, res, next) => {
  var token = req.headers['authorization'];
  if (token) {
    jwt.verify(token, "mysecret", (err, decod) => {
      if (err) {
        res.status(403).send({message: "Access forbidden, wrong token."});
      } else {
        req.decoded = decod;
        next();
      }
    });
  } else {
    res.status(403).send({message: "Access forbidden, no token provided."});
  }
});

The req.headers['authorization'] is always undefined... But when I execute the get request via Postman, the Authorization header is properly set, and I can get the token on my Node.JS server. req.headers['authorization'] 总是未定义的......但是当我通过 Postman 执行 get 请求时,Authorization 标头被正确设置,我可以在我的 Node.JS 服务器上获取令牌。

I don't understand where is my mistake... Thank's a lot for your help !我不明白我的错误在哪里...非常感谢您的帮助!

Your axios header key is "Authorization", but in node you get with "authorization".您的 axios 标头键是“授权”,但在节点中您获得“授权”。

The javascript object key is case-sensitive :D javascript 对象键区分大小写 :D

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM