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

React中Fetch发送POST请求报401错误,Postman可正常请求

React中Fetch发送POST请求出现401 Unauthorized问题的解决方法

问题描述

在基于redux-thunk的React应用中使用Fetch发送POST API请求时,出现401-Unauthorized错误,但使用相同的Authorization令牌在Postman中执行相同请求可成功响应。测试发现独立Node.js应用中用request库能成功发送请求,但该库已废弃无法在React中使用,推测是Fetch请求配置存在遗漏。

原代码如下:

export const addTodoAsync = createAsyncThunk(
  "todos/addTodoAsync",
  let token = '22e745f508990f40c97feccf5cf3397f7fbe0ae96f6b7baf051fccbcbb8267df';
  async (payload) => {
     const response = await fetch('https://gorest.co.in/public/v1/todos', {
        method: "POST",
        headers:  {
          Accept: "application/json",
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`
      },  
        body: {user_id: '6000', title: 'wakeup', status: 'pending', due_on: '2022-07-22T10:40:36.630Z+10:40'}
      });


      if (response.ok) {
      let todo = await (response.json()).data;
      return { todo };
    }
  }
);

问题原因及修复方案

  • 核心问题:请求体未序列化
    Fetch API要求POST请求的body如果是对象,必须通过JSON.stringify()转换为JSON字符串,否则服务器无法正确解析请求体,可能导致授权验证失败。

  • 语法错误修正
    原代码中createAsyncThunk的第二个参数直接声明let token,属于语法错误,需将token定义移至async函数内部或外部合适位置。

  • 添加错误处理
    原代码未处理非成功响应,补充错误捕获逻辑可帮助排查问题。

修正后的代码

export const addTodoAsync = createAsyncThunk(
  "todos/addTodoAsync",
  async (payload) => {
    const token = '22e745f508990f40c97feccf5cf3397f7fbe0ae96f6b7baf051fccbcbb8267df';
    try {
      const response = await fetch('https://gorest.co.in/public/v1/todos', {
        method: "POST",
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json",
          Authorization: `Bearer ${token}`
        },  
        // 将请求体序列化为JSON字符串
        body: JSON.stringify({
          user_id: '6000', 
          title: 'wakeup', 
          status: 'pending', 
          due_on: '2022-07-22T10:40:36.630Z+10:40'
        })
      });

      if (response.ok) {
        const data = await response.json();
        return { todo: data.data };
      } else {
        // 获取错误信息并抛出
        const errorData = await response.json();
        throw new Error(`请求失败:${response.status} - ${errorData.message || '未知错误'}`);
      }
    } catch (err) {
      throw err;
    }
  }
);

额外排查建议

  • 在浏览器开发者工具的Network面板中查看请求头,确认Authorization字段与Postman中的一致,确保token未被篡改或遗漏。
  • 检查token是否处于有效期内,若为动态获取的token,需确保请求发送时token是最新的。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 16:45:44