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

为何Authorization值未通过Request Headers传递?POST请求报500错误

问题:POST请求配置的Authorization头未生效,触发500错误

我尝试在POST请求的配置中传入token值,但该值未出现在请求头里,最终触发了500错误。

前端请求代码

export const moneyTransfer = (id, account, amount) => async ( dispatch, getState) => {
  try {
    dispatch({
      type: MONEY_TRANSFER_REQUEST,
    });

    const {
      userLogin: { userInfo },
    } = getState();

    const config = {
      headers: {
        Authorization: `Bearer ${userInfo.token}`,
      },
    };
    console.log(config);
    const { data } = await axios.post(
      `http://localhost:6969/v1/api/transferToAccountByAccountNo?senderAccountNo=${id}&receiverAccountNo=${account}&amount=${amount}`,config );
    console.log(data);
    dispatch({
      type: MONEY_TRANSFER_SUCCESS,
    });
  } catch (error) {
    dispatch({
      type: MONEY_TRANSFER_FAIL,
      payload:
        error.response && error.response.data.message
          ? error.response.data.message
          : error.message,
    });
  }
};

Chrome捕获的请求头

POST /v1/api/transferToAccountByAccountNo?senderAccountNo=5&receiverAccountNo=2&amount=123 HTTP/1.1
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-IN,en-US;q=0.9,en;q=0.8
Connection: keep-alive
Content-Length: 103
Content-Type: application/json
Host: localhost:6969
Origin: http://localhost:3000
Referer: http://localhost:3000/
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36
sec-ch-ua: "Google Chrome";v="107", "Chromium";v="107", "Not=A?Brand";v="24"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Windows"

排查方向与解决方法

  • 验证token有效性:先看console.log(config)的输出,确认Authorization字段是否有正确的token值。如果userInfo.token是undefined或空字符串,请求头自然不会包含该字段,可添加console.log(userInfo.token)直接验证。
  • 修正Axios POST参数顺序:Axios的post方法签名是axios.post(url[, data[, config]]),你当前把config作为第二个参数,Axios会将其当作请求体而非配置项。如果不需要请求体,要传空对象作为第二个参数,把config放在第三个位置:
    const { data } = await axios.post(
      `http://localhost:6969/v1/api/transferToAccountByAccountNo?senderAccountNo=${id}&receiverAccountNo=${account}&amount=${amount}`,
      {}, // 空请求体,按后端要求调整
      config
    );
    
  • 检查后端CORS配置:如果后端未允许Authorization头跨域,浏览器会在预检请求中过滤该字段。需后端在CORS配置中添加Access-Control-Allow-Headers: Authorization。
  • 排查全局拦截器:确认是否有Axios全局拦截器修改或删除了Authorization头,可暂时禁用拦截器测试。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 00:20:27