1

我有一个 HttpInterceptor 可以将本地存储中的 JWT 令牌添加到我的 http 请求的标头中。我相信我所有的 http 请求都是在没有任何标头的情况下发送的,但不明白为什么它不起作用。

我缺少什么让拦截器将标头添加到我的请求中?

我的拦截器:

import { Injectable, Injector } from '@angular/core';
import {HttpInterceptor} from "@angular/common/http";

@Injectable({
  providedIn: 'root'
})

export class TokenInterceptorService implements HttpInterceptor {

  constructor(private injector: Injector) { }

  intercept(req, next) {
    let tokenizedReq = req.clone({
      setHeaders: {
        Authorization: `Bearer ${localStorage.getItem('token')}`
      }
    })
    return next.handle(tokenizedReq)
  }
}

我的服务:

import { baseUrl } from "../environments/environment";
import { Injectable } from '@angular/core';
import {HttpClient} from "@angular/common/http";
import {Observable} from "rxjs";
@Injectable({
  providedIn: 'root'
})
export class AccountService {

  constructor(private http:HttpClient) { }

  getUser(data):Observable<any>{
    return this.http.post(`${baseUrl}/useraccount/user`, data);
  }

}
4

2 回答 2

1

你必须注册你的拦截器,例如ApplicationModule

@NgModule({
  imports: [
    HttpClientModule
  ],
  exports: [],
  providers: [
    {provide: HTTP_INTERCEPTORS, useClass: YourInterceptorClass, multi: true},
  ]
})
于 2020-10-27T13:58:16.330 回答
0

不久前我遇到了同样的问题,我意识到我的应用程序中有几个模块。因此,将拦截器放在我试图拦截的模块中,而不是放在 app 模块中,它起作用了!

我的拦截器是这样的

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        req = req.clone({
            setHeaders: {
                "Content-Type": "application/json; charset=utf-8",
                Accept: "application/json",
                Authorization: `Bearer ${AuthService.getAccessTokenFromStorage()}`,
            },
        });

        return next.handle(req);
    }
}

在我的内部模块中(例如,client.module)是这样的

...
providers: [{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }],
...
于 2021-04-17T12:50:49.673 回答