Axios Patch请求异常:无请求体时前端返回401错误
解决Axios发送无请求体PATCH请求返回401的问题
问题分析
Postman中发送无请求体的PATCH请求正常,但Axios中无论传空字符串、null还是空对象都返回401,核心原因是:
- Axios会自动将空对象
{}序列化为JSON字符串"{}",导致实际请求体不为空,Content-Length也不是0 - 不必要的
Content-Type: application/json请求头,在无请求体时可能触发服务器的验证逻辑
可行解决方案
方案1:使用axios.request方法直接配置请求
跳过axios.patch的默认data处理,直接定义请求方法和参数,确保不携带请求体:
export const somethingNeedsPatching = async (details) => { const { token } = JSON.parse(localStorage.getItem("userData")); const url = `${import.meta.env.VITE_APP_SNATCH_URL}/something/somethingPath/${details.something}`; try { const res = await axios.request({ method: 'patch', url, headers: { Authorization: `Bearer ${token}`, "Content-Length": 0 // 明确告知服务器无请求体 } }); return res; } catch (error) { console.log(error); return error.response; } };
方案2:修改axios.patch的配置,处理空请求体
传入null作为data,同时通过transformRequest移除不必要的请求头:
export const somethingNeedsPatching = async (details) => { const { token } = JSON.parse(localStorage.getItem("userData")); const url = `${import.meta.env.VITE_APP_SNATCH_URL}/something/somethingPath/${details.something}`; try { const res = await axios.patch(url, null, { headers: { Authorization: `Bearer ${token}`, "Content-Length": 0 }, transformRequest: [(data, headers) => { // 无请求体时删除Content-Type头 if (data === null) { delete headers['Content-Type']; } return data; }] }); return res; } catch (error) { console.log(error); return error.response; } };
关键注意点
- 不要在无请求体时设置
Content-Type: application/json,这会让服务器误以为有JSON请求体,触发验证失败 - 明确设置
Content-Length: 0,确保和Postman的请求行为一致 - 避免传入空对象
{},因为Axios会自动序列化它为非空的JSON字符串
内容的提问来源于stack exchange,提问作者Syed Abu Hanifah Bin Syed Azmi
相关产品推荐
相关产品推荐

