角度6-将JWT承载令牌添加到标头不工作

角度6-将JWT承载令牌添加到标头不工作,jwt,angular6,asp.net-core-2.2,Jwt,Angular6,Asp.net Core 2.2,我试图添加auth bearer令牌头,同时在angular 6中从asp.net core 2.2后端获取注释 getComment(postId: number): Observable<IComment[]>{ let headers = new HttpHeaders(); headers.append('Content-Type', 'application/json'); let authToken = localStorage.getItem('

我试图添加auth bearer令牌头,同时在angular 6中从asp.net core 2.2后端获取注释

getComment(postId: number): Observable<IComment[]>{
    let headers = new HttpHeaders();
    headers.append('Content-Type', 'application/json');
    let authToken = localStorage.getItem('auth_token');
    headers.append('Authorization', 'Bearer ' + authToken);
    console.log(authToken);
    return this.httpClient.get<IComment[]>('api/comment/post/' + postId, { headers });
  }
当我从后端的操作中删除授权时,获取评论就可以了。正如您在下图中所看到的,jwt令牌只是没有被添加到头中

邮递员:

来自chrome的标题信息

当您通过Postman说它工作正常,并且这不是CORS问题(即,CORS已启用,或者您的JS与您的API来自同一来源)时,我假设您已经订阅了返回的
Observable

上面的代码不会发出请求,除非有如下调用:

yourService.getComment(postId).subscribe(comments => { ... });

这将开始使用可观察的
并触发底层HTTP请求。

您没有在
{headers}
部分传递头。
Change
返回this.httpClient.get('api/comment/post/'+postId,{headers})
to
返回this.httpClient.get('api/comment/post/'+postId,{headers:headers})

该问题可能与CORS有关。当然,邮递员与浏览器是不同的客户端。你能告诉我你在浏览器里得到了什么样的回应吗;就像使用开发者工具和网络标签一样?最好使用拦截器来实现这些目的。请参阅示例-现在我只想用一种简单的方法将令牌添加到头中。我有很多事情要做,时间有限。你好,我已经试过了。{headers:headers}但这不起作用。您好,是的,我使用订阅。当我放入[AllowAnonymous]并执行该操作时,我收到了预期的注释列表。this._commentService.getComment(this.activeRoute.snapshot.params.id).subscribe(data=>this.comments=data);
yourService.getComment(postId).subscribe(comments => { ... });