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
相关产品推荐
相关产品推荐

