Angular 虽然令牌已正确加载,但出现未经授权的错误

Angular 虽然令牌已正确加载,但出现未经授权的错误,angular,auth0,angular2-jwt,Angular,Auth0,Angular2 Jwt,我更新了Angular 6应用程序,以便它使用库。在我现在更新了我的服务之后,我的API返回了一个401 Unauthorized错误,尽管令牌正确地附加到了头上 使用Angular的HttpClient发送的任何请求都将自动附加一个令牌作为授权标头 以下是相关文件: 因此,据我正确理解,我不需要在任何时候加载我的令牌,只要我想发出请求,就可以将其附加到头上,因为它会自动加载。这是我的代码: 应用程序模块.ts import { JwtModule } from '@auth0/angular-

我更新了Angular 6应用程序,以便它使用库。在我现在更新了我的服务之后,我的API返回了一个
401 Unauthorized
错误,尽管令牌正确地附加到了头上

使用Angular的HttpClient发送的任何请求都将自动附加一个令牌作为授权标头

以下是相关文件:

因此,据我正确理解,我不需要在任何时候加载我的令牌,只要我想发出请求,就可以将其附加到头上,因为它会自动加载。这是我的代码:

应用程序模块.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'],
      }
    }),
import { HttpClient } from '@angular/common/http';

  constructor(
    public http: HttpClient
  ) {}

  getProfile() {
    return this.http.get<profile>('http://localhost:3000/users/profile');
  }
auth.service.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'],
      }
    }),
import { HttpClient } from '@angular/common/http';

  constructor(
    public http: HttpClient
  ) {}

  getProfile() {
    return this.http.get<profile>('http://localhost:3000/users/profile');
  }
从'@angular/common/http'导入{HttpClient};
建造师(
公共http:HttpClient
) {}
getProfile(){
返回此.http.get('http://localhost:3000/users/profile');
}
如果我使用本地存储中的邮递员令牌,一切正常,我会返回正确的配置文件数据。如果我使用我的Angular应用程序,它将无法工作

试试这个

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

这很好,但不像文档中说的那样,每个请求都会自动发送一个头:/