You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular调用后端List接口时出现401 Unauthorized错误求助

Angular调用后端List接口返回401 Unauthorized问题修复

问题现象

在Angular项目中调用后端List接口时,持续收到401 Unauthorized错误,无法正常获取接口响应。

错误原因分析

从提供的代码中可定位两个核心问题:

  1. Authorization请求头格式错误:AuthInterceptor中拼接Bearer与令牌时缺少空格,后端无法正确识别令牌格式,导致认证失败。
  2. 令牌获取逻辑错误: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,
  },
],

验证方法

  1. 登录成功后,打开浏览器开发者工具的网络面板;
  2. 触发List接口调用,查看请求的Authorization头,确认格式为Bearer {有效令牌内容};
  3. 核对令牌内容与localStorage中AUTH_KEY对应的access_token字段完全一致。

内容的提问来源于stack exchange,提问作者posky

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 04:35:20