【问题标题】:JWT authentication working with $http.get but not with $http.postJWT 身份验证适用于 $http.get 但不适用于 $http.post
【发布时间】:2016-11-11 11:54:05
【问题描述】:

我是 MEAN 堆栈的新手。 我正在使用 jwt 来验证 api 端点 '/api/candidates'

在客户端/angular js 服务中,我有以下条目

resumeFactory.get = function(candidateName) {
   return  $http.get('/api/candidates', {
      headers: {
        Authorization: 'Bearer '+ authenticationService.getToken()     
   });
};

在服务器端我有:

app.get('/api/candidates', auth, function (req, res) {
if (!req.payload._id) {
    //user not logged in
    console.log(req);
    res.status(401).json({"message": "no  user logged in from candidates"});
}
else {
    Candidate.find({}, function (err, candidates) {
        if (err) {
            res.send(err);
        }
        res.json(candidates);
    });
}
});

这很好用。即 'auth' 能够从标头中提取令牌

当我将所有内容更改为 post 而不是 get 时:

客户端

$http.post()  

服务器端

app.post()

我从 jwt 收到如下错误:

UnauthorizedError: No authorization token was found

对正在发生的事情有什么建议吗?我可以使用 get,但我想知道为什么 post 不起作用

【问题讨论】:

  • 如果您真的在标头中发布该令牌,请检查开发工具。
  • @Nonemoticoner 我无法在开发工具中找到它。不确定如何在请求中查找标头
  • @Nonemoticoner - 我终于能够弄清楚如何检查标头 Networks->XHR

标签: angularjs node.js jwt mean express-jwt


【解决方案1】:

$http.post 配置是third argument,而不是第二个(like in get),因此请相应地更新您的参数:

$http.post('/url', { cool: postData }, {
  headers: {
    Authorization: 'Bearer '+ authenticationService.getToken()
  }    
});

更好的是,use an interceptor 将 Authorization 标头添加到所有请求。

【讨论】:

  • 谢谢安迪·加斯凯尔。
猜你喜欢
  • 2021-03-18
  • 2014-08-16
  • 2017-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-15
相关资源
最近更新 更多