我目前在 Angular 应用程序中遇到 HTTP 拦截器问题。我创建了一个拦截器来将身份验证令牌添加到 HTTP 请求的标头中,但它似乎在 HTTP 调用期间没有触发。
这是我的拦截器的代码:
import { HttpInterceptorFn } from '@angular/common/http';
export const TokenInterceptor: HttpInterceptorFn = (req, next) => {
if (req.headers.get('No-Auth') == 'True') {
return next(req);
}
if (typeof window !== 'undefined') {
const authToken = localStorage.getItem('authToken');
if (!authToken) {
//TODO redirection vers la page d'authentification
}
const authReq = req.clone({
setHeaders: {
Authorization: `Bearer ${authToken}`,
},
});
return next(authReq);
}
return next(req);
}
我已经在 Angular 模块中正确注册了拦截器,但它似乎在 HTTP 调用期间没有触发。您对可能导致此问题的原因有什么想法吗,尤其是考虑到我使用的是 Angular 17?我错过了拦截器配置中的任何内容吗?
import { ApplicationConfig } from '@angular/core';
import { provideRouter, withComponentInputBinding } from '@angular/router';
import { routes } from './app.routes';
import { provideClientHydration } from '@angular/platform-browser';
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { TokenInterceptor } from '../domain/services/interceptor-token.service';
export const appConfig: ApplicationConfig = {
providers: [provideRouter(routes, withComponentInputBinding()), provideClientHydration(), provideHttpClient(withInterceptors([
TokenInterceptor
]))]
}
任何帮助将不胜感激。预先感谢!
你尝试了什么: 我在 Angular 17 中实现了一个 HTTP 拦截器,以将身份验证令牌添加到 HTTP 请求的标头中。我在 Angular 模块中注册了拦截器,并确保它包含在提供程序列表中。
您期待什么: 我期望在 HTTP 调用期间触发拦截器,按预期将身份验证令牌添加到标头中。目标是使用从 localStorage 检索到的身份验证令牌来保护我的 HTTP 请求。
观察/问题: 尽管注册正确,拦截器似乎在 HTTP 调用期间并未触发。我已验证 No-Auth 标头在应触发时不存在,并且我使用的是 Angular 版本 17。
向社区提出的问题: 对可能导致此问题的原因有何见解?我是否错过了任何 Angular 17 特定的配置或 HTTP 拦截器的注意事项?
附加信息:
角度版本:17 代码片段:包括拦截器实现和模块注册的相关部分。
导出 const loggerInterceptor : HttpInterceptorFn = (req,next) =>{
// Write your logic
console.log("Inside interceptor")
const token = localStorage.getItem('token');
const authReq = req.clone({headers : req.headers.set('Authorization',`Bearer
${token}`)})
return next(authReq);
};
在app.config.ts中
提供HttpClient(withInterceptors([loggerInterceptor]))
这就是我使用它的方式,它拦截所有请求