在标头中使用JWT令牌从API提取的最佳方法

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

  • 从API提取生成的HTML的最佳方法是什么? (获取vs HttpClient vs AJAX vs ???)
  • 如何从概念上将路由转换为从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()"

我的尝试无效。我可能在逻辑上和设计上都犯了一些错误。

holylai 回答:在标头中使用JWT令牌从API提取的最佳方法

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));
}

只需尝试一下

本文链接:https://www.f2er.com/3080029.html

大家都在问