【问题标题】:Angular 6 - Add JWT bearer token to header not workingAngular 6 - 将 JWT 不记名令牌添加到标头不起作用
【发布时间】:2019-02-27 12:27:30
【问题描述】:

我正在尝试添加身份验证承载令牌标头,同时从角度 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 });
  }

这段代码不起作用。我从 console.log(authToken) 得到一个值。当我在 Postman 中复制令牌时,一切正常。

我在服务中的登录功能。这很好,我正在从后端获取令牌。

 login(login: ILogin) {
    console.log(login);
    return this.http
      .post('api/auth/login', login)
      .pipe(map((res: any) => {
        localStorage.setItem('auth_token', res.auth_token);
        this.loggedIn = true;
        this._authNavStatusSource.next(true);
        return true;
      }));
  }

当我从后端的操作中删除授权时,获取 cmets 工作正常。正如您在下图中看到的,jwt 令牌只是没有被添加到标题中。

邮递员:

来自 chrome 的标题信​​息

【问题讨论】:

  • 该问题可能与 CORS 有关。当然,Postman 是不同于浏览器的客户端。您能说出您在浏览器中得到的响应吗?喜欢使用开发者工具和网络标签?
  • 最好使用 Interceptor 来达到这些目的。查看示例 - stackoverflow.com/questions/51396931/…
  • 现在我只想用简单的方法将令牌添加到标题中。学校有很多事情要做,时间有限。

标签: jwt angular6 asp.net-core-2.2


【解决方案1】:

当您说它通过 Postman 运行良好,并且这不是 CORS 问题(即,启用了 CORS,或者您的 JS 与您的 API 来自同一来源)时,我假设您已经订阅到返回的Observable&lt;IComment[]&gt;。

上面的代码不会发出请求,直到某个地方出现如下所示的调用:

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

这将开始使用 Observable 并触发底层 HTTP 请求。

【讨论】:

  • 您好,是的,我使用订阅。当我输入 [AllowAnonymous] 和操作时,我会按预期收到评论列表。 this._commentService.getComment(this.activeRoute.snapshot.params.id).subscribe(data => this.cmets = data);
【解决方案2】:

您没有传递 { headers } 部分中的标题。 将return this.httpClient.get&lt;IComment[]&gt;('api/comment/post/' + postId, { headers }); 更改为return this.httpClient.get&lt;IComment[]&gt;('api/comment/post/' + postId, { headers: headers });

【讨论】:

  • 你好,我已经试过了。 { headers: headers} 但这不起作用。
猜你喜欢
  • 2019-05-28
  • 1970-01-01
  • 1970-01-01
  • 2021-04-13
  • 2022-11-26
  • 2020-11-13
  • 2021-07-22
  • 2018-12-29
  • 2019-03-23
相关资源
最近更新 更多