【问题标题】:Optimal way to fetch from API with JWT tokens in the header在标头中使用 JWT 令牌从 API 获取的最佳方式
【发布时间】:2019-11-18 14:57:48
【问题描述】:

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

  • 从 API 获取生成的 HTML 的最佳方法是什么? (Fetch 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()"

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

【问题讨论】:

  • 看看Angulars HTTPInterceptor 为每个请求发送一个令牌。
  • @DarrenLamb 它应该与像 httpOptions = { // the jwthere below is obviously only a placeholder headers: new HttpHeaders({ 'authorization': 'jwthere' }) }; 这样的 HttpClientModule 一起使用,它不需要拦截,因此会增加延迟。这也来自 Angular 文档。
  • @JasonWhite 给我错误Cannot find name 'RequestOptions'.
  • @JasonWhite "No overload matches this call.\n The last overload gave the following error.\n Argument of type '{ headers: Headers; }' is not assignable to parameter of type '{ headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: \"body\"; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: \"json\"; withCredentials?: boolean; }'.\n Types of property 'headers' are incompatible.\n Type 'Headers' is not assignable to type 'HttpHeaders' ...
  • “从后端 api 获取 HTML 模板”是什么意思?如果您要加载在服务器上动态生成的 HTML,为什么不回到 10 年前使用 ASP.NET?

标签: angular api fetch httpclient api-design


【解决方案1】:
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));
}

试试这个

【讨论】:

  • Duplicate identifier 'httpOptions'., Subsequent property declarations must have the same type. Property 'httpOptions' must be of type '{ headers: HttpHeaders; }', but here has type 'any'., ';' expected. :/
  • @Munchkin - 删除构造函数上方的行。请查看更新后的答案
  • Property 'get' does not exist on type 'HttpClientModule'.whyyy
  • @Munchkin - 你在app.component.ts 中导入了HttpClientModule 你只需要在import 部分中添加HttpClientModule,该部分将从import { HttpClient } from '@angular/common/http'; 导入
  • @Munchkin - 不要使用 HttpClientModule 而是在构造函数中使用 HttpClient
猜你喜欢
  • 2020-11-16
  • 2015-07-03
  • 2020-11-30
  • 1970-01-01
  • 2021-06-17
  • 1970-01-01
  • 2020-05-27
  • 2021-04-20
  • 2018-12-04
相关资源
最近更新 更多