使用 $http.get 但不使用 $http.post 的 JWT 身份验证
JWT authentication working with $http.get but not with $http.post
我是 MEAN 堆栈的新手。
我正在使用 jwt 来验证 api 端点 '/api/candidates'
在 client-side/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' 能够从 header
中提取令牌
当我将所有内容更改为 post 而不是 get :
在客户端
$http.post()
在服务器端:
app.post()
我从 jwt 得到如下错误:
UnauthorizedError: No authorization token was found
对正在发生的事情有什么建议吗?。我可以使用 get 但我想知道为什么 post 不起作用
$http.post
配置是 third argument, not second (like in get
) 因此请相应地更新您的参数:
$http.post('/url', { cool: postData }, {
headers: {
Authorization: 'Bearer '+ authenticationService.getToken()
}
});
更好的是,use an interceptor 将授权 header 添加到所有请求。
我是 MEAN 堆栈的新手。 我正在使用 jwt 来验证 api 端点 '/api/candidates'
在 client-side/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' 能够从 header
中提取令牌当我将所有内容更改为 post 而不是 get :
在客户端
$http.post()
在服务器端:
app.post()
我从 jwt 得到如下错误:
UnauthorizedError: No authorization token was found
对正在发生的事情有什么建议吗?。我可以使用 get 但我想知道为什么 post 不起作用
$http.post
配置是 third argument, not second (like in get
) 因此请相应地更新您的参数:
$http.post('/url', { cool: postData }, {
headers: {
Authorization: 'Bearer '+ authenticationService.getToken()
}
});
更好的是,use an interceptor 将授权 header 添加到所有请求。