Angular调用后端List接口时出现401 Unauthorized错误求助
问题现象
在Angular项目中调用后端List接口时,持续收到401 Unauthorized错误,无法正常获取接口响应。
错误原因分析
从提供的代码中可定位两个核心问题:
- Authorization请求头格式错误:
AuthInterceptor中拼接Bearer与令牌时缺少空格,后端无法正确识别令牌格式,导致认证失败。 - 令牌获取逻辑错误:
AuthInterceptor直接从localStorage读取AUTH_KEY对应的完整JSON字符串,而非从中提取有效的access_token字段,传递的内容并非后端所需的认证令牌。
修复步骤
1. 修正AuthInterceptor的令牌获取与请求头格式
修改auth.interceptor.ts,注入AuthService以获取正确的令牌,并修正Bearer与令牌间的空格:
import { HttpHandler, HttpInterceptor, HttpRequest, } from '@angular/common/http'; import { AuthService } from '../services/auth.service'; import { Injectable } from '@angular/core'; @Injectable() export class AuthInterceptor implements HttpInterceptor { constructor(private authService: AuthService) {} intercept(req: HttpRequest<any>, next: HttpHandler) { const token = this.authService.getToken(); if (token) { const authReq = req.clone({ headers: req.headers.set('Authorization', `Bearer ${token}`), }); return next.handle(authReq); } return next.handle(req); } }
2. 验证依赖注入配置
确保AppModule中已正确注册AuthInterceptor及AuthService(现有配置已满足,无需额外修改):
// app.module.ts中相关配置片段 providers: [ AuthService, // ...其他提供者 { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true, }, ],
验证方法
- 登录成功后,打开浏览器开发者工具的网络面板;
- 触发List接口调用,查看请求的
Authorization头,确认格式为Bearer {有效令牌内容}; - 核对令牌内容与
localStorage中AUTH_KEY对应的access_token字段完全一致。
内容的提问来源于stack exchange,提问作者posky
相关产品推荐
相关产品推荐

