使用axios与vuex发送patch请求时response.data为空如何解决
问题根因
你遇到的问题核心是后端返回了204状态码:
HTTP协议中204 No Content的标准语义是「服务器已成功处理请求,但无任何响应体返回」。即使你在后端代码中写了res.json({ data: updatedUser }),浏览器和axios也会自动丢弃204响应携带的所有内容,因此response.data必然为空。
解决方案
有两种可选方案,优先推荐第一种:
方案1:修改后端响应状态码(推荐)
将后端控制器的响应状态码从204改为200即可,200状态码允许携带响应体,修改后代码如下:
exports.updateMe = catchAsync(async (req, res, next) => { const updatedUser = await User.findByIdAndUpdate( req.body.id, { name: req.body.name, email: req.body.email }, { new: true, runValidators: true } ); // 把204改成200 res.status(200).json({ data: updatedUser }); });
修改后前端就能正常拿到response.data的值。
方案2:保留204状态码,前端自行组装更新数据
如果业务逻辑要求必须使用204状态码,你可以直接用提交的payload + 本地存储的用户ID组装更新后的用户数据,提交给vuex的mutation即可:
async updateMe({ commit }, payload) { let id = localStorage.getItem('userId'); let user = { name: payload.name, email: payload.email, id: id }; try { await axios.patch( `http://localhost:3000/api/v1/users/updateMe`, user ); // 直接用本地组装的user更新vuex commit('setUpdatedUser', user); } catch (err) { console.log(err); } }
该方案的缺点是无法确保本地数据和数据库实际存储的更新后数据完全一致,除非有特殊要求否则不建议使用。
额外校验建议
你可以额外在后端代码中添加空值判断,避免更新不存在的用户时无错误提示:
exports.updateMe = catchAsync(async (req, res, next) => { const updatedUser = await User.findByIdAndUpdate( req.body.id, { name: req.body.name, email: req.body.email }, { new: true, runValidators: true } ); // 新增空值判断 if (!updatedUser) { return res.status(404).json({ message: '用户不存在' }) } res.status(200).json({ data: updatedUser }); });
内容的提问来源于stack exchange,提问作者Ksharples431
相关产品推荐
相关产品推荐

