1

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

在客户端/角度 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'能够从标头中提取令牌

当我将所有内容更改为发布而不是获取时:

客户端

$http.post()  

服务器端

app.post()

我从 jwt 收到如下错误:

UnauthorizedError: No authorization token was found

关于发生了什么的任何建议?我可以使用get但我想知道为什么post不起作用

4

1 回答 1

1

使用$http.postconfig 是第三个参数,而不是第二个(如 in get,因此相应地更新您的参数:

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

更好的是,使用拦截器将 Authorization 标头添加到所有请求中。

于 2016-07-08T20:30:49.097 回答