首页 > 解决方案 > 在标头中使用 JWT 令牌从 API 获取的最佳方式

问题描述

我正在重写我的 Angular 应用程序,而不是让路由(客户端)从后端 API(Pug,express.js)获取 HTML 模板。 我需要在每次请求访问 API 时在标头中发送一个 JWT 令牌。我的 API 还支持正文中的令牌。

我的尝试:

 httpClient: any;
  httpOptions = {
// the jwthere below is obviously only a placeholder
    headers: new HttpHeaders({ 'authorization': 'jwthere' })
  };
  constructor(private http: HttpClient) { }

  ngOnInit() {

  }

  fetchDashboard() {
    this.http.get('localhost:3000/dashboard').subscribe(j => console.log(j));
  }
}

然后在html中我将函数定义为: (click)="fetchDashboard()"

我的尝试不起作用。我可能犯了一些逻辑和设计缺陷。

标签: angularapifetchhttpclientapi-design

解决方案


httpOptions = {
  headers: new HttpHeaders({
    'Content-Type':  'application/json',
    'Authorization': 'my-auth-token'
  })
};

constructor(private http: HttpClient) { }

ngOnInit() {

}
fetchDashboard() {
    this.http.get('localhost:3000/dashboard', this.httpOptions).subscribe(j => console.log(j));
}

试试这个


推荐阅读