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

使用axios发送post请求返回401未授权错误,Insomnia请求正常如何解决

问题根因
  • HTTP客户端请求参数传位错误,你使用的AlleSys.post(推测为Axios封装实例)标准传参规则为post(请求地址, 请求体, 配置项),你把headers直接合并到了请求体参数里,后端不会从请求体里读取Authorization头,因此识别不到令牌。
  • headers结构定义错误,你额外套了一层header字段,正确配置下配置项的顶级字段就是headers,不需要再嵌套一层。
  • CORS配置未允许Authorization头,你的后端CORS配置没有显式声明允许前端传递Authorization头,跨域预检请求会直接被拦截,导致正式请求无法发送。
修复步骤

前端Redux Action代码修复

export const createPost = ( formValues: any) => async(dispatch: any, getState: any) => {
  const { userId } = getState().auth;
  const token = userId

  const config = {
    headers: {
      'Content-Type' : 'application/json',
      'Accept' : 'application/json',
      Authorization: `Bearer ${token}`
    },
    // 后端开启了credentials:true,前端必须对应开启配置
    withCredentials: true
  };
  // 第二个参数传请求体,第三个参数传配置项
  const response = await AlleSys.post('/posts', formValues, config)
  dispatch({type: CREATE_POST, payload: response.data})
}

后端CORS配置修复

const corsOptions ={
    origin:'http://localhost:3000',
    credentials:true,
    optionSuccessStatus:200,
    // 显式允许Authorization头跨域传递
    allowedHeaders: ['Content-Type', 'Authorization', 'Accept']
}
app.use(cors(corsOptions))

修复完成后可以打开浏览器控制台的网络面板,确认请求头中已经携带Authorization: Bearer xxx字段即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 11:54:03