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

使用HTTP.post携带正确Token仍出现401 Unauthorized错误的解决方法

问题分析与解决方案

你的代码存在一个关键错误:Angular HttpClient.post 方法的参数顺序不正确。post 方法的第二个参数是请求体(body),第三个参数才是包含请求头、withCredentials 等的配置选项对象。你现在把配置对象放在了请求体的位置,导致服务器根本没收到你设置的 Authorization 头,因此返回401未授权错误。

修正后的代码

deleteOrder(orderCode: string) {
    const deleteOrderUrl = this.occEndpointsService.buildUrl(`/orders/${orderCode}/delete`);
    return this.clientTokenService.getClientToken().pipe(
      switchMap((token) => {
        // 正确传递参数:url、请求体(无需请求体则传{}或null)、配置选项
        return this.http.post(deleteOrderUrl, {}, {
          headers: {
            'Authorization': `Bearer ${token.access_token}`
          },
          withCredentials: true,
        }).pipe(
          map((result: any) => result),
          catchError((error: any) => throwError(error))
        );
      })
    );
}

额外检查点

  • 若接口无需请求体,第二个参数传 {} 或 null 均可,确保配置选项处于第三个参数位置。
  • 核对 token.access_token 的值与Postman中使用的完全一致,避免拼写、大小写或格式错误。
  • 通过浏览器开发者工具的Network面板查看实际请求头,确认 Authorization 头是否已正确携带。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 09:17:39