angular - 尽管正确加载了令牌,但出现未经授权的错误
问题描述
我更新了我的 Angular 6 应用程序,以便它使用auth0/angular2-jwt库。在我现在更新我的服务后,我401 Unauthorized
从我的 API 中收到一个错误,尽管一个令牌已正确附加到标头。
使用 Angular 的 HttpClient 发送的任何请求都会自动附加一个令牌作为 Authorization 标头。
这是相关的文档:Usage Injection
所以据我正确理解,我不需要在我想要发出请求的任何时候加载我的令牌,而是将它附加到标头,因为它会自动加载。这是我的代码:
app.module.ts
import { JwtModule } from '@auth0/angular-jwt';
import { HttpClientModule } from '@angular/common/http';
imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule,
HttpClientModule,
JwtModule.forRoot({
config: {
tokenGetter: () => {
return localStorage.getItem('id_token');
},
throwNoTokenError: true,
whitelistedDomains: ['localhost:3000'],
}
}),
auth.service.ts
import { HttpClient } from '@angular/common/http';
constructor(
public http: HttpClient
) {}
getProfile() {
return this.http.get<profile>('http://localhost:3000/users/profile');
}
如果我将 Postman 与我的 localStorage 中的令牌一起使用,则一切正常,并且我会取回正确的配置文件数据。如果我使用我的 Angular-App,它就不起作用。
解决方案
试试这个。
import {HttpClient, HttpHeaders} from '@angular/common/http';
return this.http
.get('http://localhost:3000/users/profile', {
headers: new HttpHeaders().set('Authorization', `Bearer ${this.localStorage.getItem('id_token')}`)
});
推荐阅读
- javascript - 如何从路由参数中获取值并将其保存在 Nuxtjs 中的数据中
- python - 如何检测谁删除了反应 discord.py
- r - 在 R 中使用 FeNmlm 包进行固定效应的重力估计
- python - ImportError: 无法从 'gensim.matutils' (d:\python\lib\site-packages\gensim\matutils.py) 导入名称 'softcossim'
- javascript - 如何向用户展示特定的网页设计?
- java - 无法从“15”确定 java 版本
- matlab - 在这种情况下,是否有任何类似于 Matlab 中的 GOTO 的语法或方式?
- loops - 3 个变体的集群补丁,每个变体 100 个计数
- amazon-web-services - AWS:存储和分析游戏数据架构(elastic or athena or kinesis)
- arrays - 计算要截断的目标大小以适合特定大小内的字符串