我是平均堆栈的新手,使用passport-jwt进行授权。我已经启用了cors
来获取外部的获取/发布请求。所以我能够使用angular 7发布/获取数据,但无法授权JWT生成的令牌。有一件事,授权在Firefox上使用RestClient Addon时很好(类似于chrome中的邮递员),你可以在这张图片中找到。
但是当试图从使用角度的同一api获取请求然后得到这个这是我的角度服务
getProfile():Observable<any>{
let headers = new HttpHeaders();
console.log(localStorage.getItem('mean_token'));
headers.append('Authorization', localStorage.getItem('mean_token'));
return this.http.get('http://localhost:8888/users/profile', {headers:headers});
}
这是节点快速代码
//profile
router.get('/profile', passport.authenticate('jwt', {session:false}), (req, res, next)=>{
console.log("profle called");
res.json({user:req.user});
});
挣扎了很久才找到答案,请帮帮我。
注意:其他用于get / post的API正在使用angular查找。
这是我找到的新版角度(> 6)的解决方案。 headers.append()
不起作用,因为HttpHeaders
对象是不可变的。你需要将标题更改为:
const headers = new HttpHeaders({ 'Content-Type': 'application/json',
'Authorization': localStorage.getItem('mean_token') });
现在一切都很好..