React+Node.js中Axios Delete请求体为空的问题求助
问题解决:Axios Delete请求体为空的处理
核心原因
Axios的delete方法参数结构和post存在差异:
post(url, data, config):第二个参数直接对应请求体数据delete(url, config):第二个参数是配置对象,请求体数据必须嵌套在config.data字段中
你当前直接把id作为第二个参数传给delete,Axios不会将其识别为请求体,导致后端req.body为空。
解决方案1:修正Axios Delete请求写法
修改前端deleteClothes函数,将id放入配置对象的data属性中:
export const deleteClothes = async (id) => { id.id = Number(id.id) const {data} = await $authHost.delete('api/clothes', { data: id }) return data }
调整后Axios会正确将id作为请求体发送,后端req.body即可获取到数据。
解决方案2:使用URL参数传递ID(推荐REST规范)
Delete请求更推荐通过URL参数传递资源ID,这更符合REST设计原则:
前端代码修改:
export const deleteClothes = async (id) => { const clothesId = Number(id.id) const {data} = await $authHost.delete(`api/clothes/${clothesId}`) return data }
后端代码修改:
async delete(req, res) { const { id } = req.params // 从URL参数中获取ID await Clothes.destroy({ where:{ id: id } }) return res.json(`Clothes deleted: ${id}`) }
同时需确保后端路由配置对应调整,比如Express框架中:
router.delete('/api/clothes/:id', yourController.delete)
额外验证
确认后端已配置JSON请求体解析中间件(如Express的express.json()),由于你的Post请求正常运行,该配置大概率已存在,可跳过此步骤。
内容的提问来源于stack exchange,提问作者DRx
相关产品推荐
相关产品推荐

