Angular 为什么我在使用拦截器时收到401错误

Angular 为什么我在使用拦截器时收到401错误,angular,Angular,我正在为支持JWT的API开发angular 9 SPA 试图实现下面的拦截器,但收到401错误。可能出了什么问题。 注意:没有拦截器,工作正常 import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from "@angular/common/http"; import { AuthService } from "../services/security/auth.servi

我正在为支持JWT的API开发angular 9 SPA

试图实现下面的拦截器,但收到401错误。可能出了什么问题。 注意:没有拦截器,工作正常

import {
  HttpEvent,
  HttpHandler,
  HttpInterceptor,
  HttpRequest
} from "@angular/common/http";

import { AuthService } from "../services/security/auth.service";
import { Injectable } from "@angular/core";
import { Observable } from "rxjs";

@Injectable()
export class AddHeaderInterceptor implements HttpInterceptor {
  constructor(private authService: AuthService) {}

  intercept(
    request: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    let jsonRequest: HttpRequest<any> = request.clone({
      setHeaders: {
        "Content-Type": "application/json",
        Authorization: "Bearer " + this.authService.auth.bearerToken,
      },
    });

    return next.handle(jsonRequest);
  }
}
导入{
HttpEvent,
HttpHandler,
HttpInterceptor,
HttpRequest
}来自“@angular/common/http”;
从“./services/security/auth.service”导入{AuthService}”;
从“@angular/core”导入{Injectable}”;
从“rxjs”导入{observeable};
@可注射()
导出类AddHeaderInterceptor实现HttpInterceptor{
构造函数(私有authService:authService){}
拦截(
请求:HttpRequest,
下一步:HttpHandler
):可见{
让jsonRequest:HttpRequest=request.clone({
集合标题:{
“内容类型”:“应用程序/json”,
授权:“持有人”+this.authService.auth.bearerToken,
},
});
返回next.handle(jsonRequest);
}
}

您得到的原因

401错误

您的请求中没有添加
承载令牌

另一方面,
拦截器
代码是一个非常简单的代码,应该可以工作

导致它无法工作的原因可能是:

  • @NgModule
    的提供程序部分未提供
  • @NgModule
    中提供,但未正确定义
  • 在错误的
    模块中提供。ts
  • 因此,解决方案是在侦听器所属的正确模块(
    SharedModule
    /
    AppModule
    /
    WhateverModule
    )中包含以下代码

    //import { AddHeaderInterceptor } from "....."
        
    
    @NgModule({
              declarations: [
                 ...
              ],
              imports: [
                 ...
              ],
              providers: [
                ...
                { provide: HTTP_INTERCEPTORS, useClass: AddHeaderInterceptor, multi: true }
              ]
    

    授权是否已成功添加到头上?你们在控制台里看到了吗?看起来不错!返回前进行调试,查看
    this.authService.auth.bearerToken
    是否具有您期望的值