angular - 在标头中使用 JWT 令牌从 API 获取的最佳方式
问题描述
我正在重写我的 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()"
我的尝试不起作用。我可能犯了一些逻辑和设计缺陷。
解决方案
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));
}
试试这个
推荐阅读
- java - Oracle Weblogic 12c 关闭不适用于两个端口
- r - 用不规则变化的数据构建时间序列数据集
- orientdb - OrientDB 对象数据库和 JPA 可靠性
- c# - RegisterClassHandler 中的 classType 参数
- r - 在 r 的预测包中首次计算预测时,请选择更长的时间范围
- ruby-on-rails - S3 中的 ActiveStorage 和层次结构
- kubernetes - RabbitMQ 节点无法发现彼此并加入集群
- string - Bash:重复字符可变次数
- fortran - Fortran 95 分段错误(核心转储)
- redux - 具有多个 subreducer 的 CombineReducers 与在同一对象/映射上设置键值的 reducer