我更新了我的 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,它就不起作用。