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

Angular添加商品到购物车POST请求返回401 token无效问题排查

问题分析与修复方案

核心错误:HttpClient.post参数顺序完全错误

你的cart.service.ts里httpClient.post的参数传递顺序搞反了,这是触发401错误的直接原因。

Angular的HttpClient.post固定参数顺序是:url → 请求体body → 请求配置options。你现在把请求头、响应模式这些配置项当成了请求体传给后端,导致实际请求里根本没带上有效的Authorization头,API自然返回token_invalidate。

修复后的cart.service.ts代码

addUpdateProductToCart(quantity: number, produkt: Product) {
  return from(Preferences.get({ key: 'TOKEN_KEY' })).pipe(
    switchMap(token => {
      const headers = new HttpHeaders().set('Authorization', `Bearer ${token.value}`);
      let params = new HttpParams();
      params = params.append('product', produkt.id);
      params = params.append('quantity', quantity.toString()); // 把数字转成字符串,避免后端参数解析异常
      
      // 正确的参数传递顺序:URL → 空请求体(如果后端不需要POST数据)→ 配置项(headers/params/observe)
      return this.httpClient.post(`${environment.apiUrl}cart`, {}, {
        headers,
        params,
        observe: 'response'
      });
    }),
    catchError(err => {
      console.log(err.status);
      if (err.status === 400) {
        console.log(err.error.message);
      }
      if (err.status === 401) {
        this.authService.logout();
        this.router.navigateByUrl('/login', { replaceUrl: true });
      }
      return EMPTY;
    }),
  );
};

其他需要排查的点

  • TOKEN有效性检查:在switchMap里打印token.value,确认拿到的token是完整、未过期的,格式符合后端要求(比如有没有多余的空格)。
  • 商品数量更新逻辑:incrementQty里的this.products[index].step += 1.00,要确保produkt和this.products[index]是同一个对象引用,避免视图显示的数量和实际传给API的不一致。
  • 参数类型匹配:后端可能要求quantity是字符串类型,所以修复代码里把数字转成了字符串,避免类型不匹配导致的隐性错误。

额外优化建议

可以在获取token时先做校验,如果没有token直接跳登录,减少无效请求:

switchMap(token => {
  if (!token?.value) {
    this.router.navigateByUrl('/login', { replaceUrl: true });
    return EMPTY;
  }
  // 后续请求逻辑...
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 09:05:19