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

Axios中Auth-Token未成功分配至请求头问题排查

问题解决:Axios请求中Auth-Token未被分配到请求头

你的代码核心问题是axios.post的参数结构错误,导致headers未被正确识别。

错误原因

axios.post的标准语法为:

axios.post(url, 请求体数据, 配置对象)

你把请求体和headers配置混在了第二个参数里,axios会将这个整体当作请求体数据处理,而非配置项,因此请求头中不会包含auth-token。

修正后的代码

await axios
  .post("http://localhost:5000/books/addBook",
    // 第二个参数:请求体数据
    {
      name: String(inputs.name),
      author: String(inputs.author),
      description: String(inputs.description),
      price: Number(inputs.price),
      image: String(inputs.image),
      available: Boolean(checked),
    },
    // 第三个参数:配置对象,包含headers
    {
      headers: {
        "auth-token": localStorage.getItem('token'),
        // Content-Type可省略,axios会自动为JSON请求设置该头
        // 'Content-Type': 'application/json'
      }
    }
  )
  .then((res) => res.data);

额外检查项

  • 确认localStorage.getItem('token')能获取到有效值,避免因token为undefined导致请求头缺失
  • 若后端对请求头键名大小写敏感,需确保auth-token的写法与后端要求完全一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 12:03:14