如何在React中借助Axios携带查询参数调用API端点更新数据
问题信息整理
- API端点:
/api/user/self/,支持GET和PUT请求 - 更新用户信息需发送PUT请求,携带JSON格式的用户文档:
{ "name": "Test", "communications": { "email": { "email": "test@user.com", "notifications": true }, }, }
- Express后端PUT接口配置:
app.put("/api/user/self", (req, res) => { const queryParams = req.query; res.json({ queryParams }); });
- 前端已实现的Axios GET请求:
useEffect(() => { axios .get("http://localhost:8000/api/user/self") .then((res) => { console.log(res); setUser(res.data); }) .catch((err) => { console.log(err); }); }, []);
- 问题:无法通过Axios发起PUT请求更新数据
- Postman测试情况:
请求地址:http://localhost:8000/api/user/self?name=test5
返回结果:
{ "queryParams": { "name": "test5" } }
解决步骤
1. 修复Express后端配置
当前后端仅读取URL查询参数,但更新用户信息应该从请求体的JSON数据中获取内容,需先添加JSON解析中间件,再修改接口逻辑:
// 在所有路由之前添加JSON解析中间件 app.use(express.json()); // 修改PUT接口逻辑 app.put("/api/user/self", (req, res) => { // 从请求体获取更新的用户数据 const updatedUserData = req.body; // 此处可添加数据库更新逻辑,比如找到对应用户并修改字段 // 示例:userModel.findByIdAndUpdate(userId, updatedUserData, { new: true }) // 返回更新结果 res.json({ message: "用户信息更新成功", updatedUser: updatedUserData }); });
2. 实现React端Axios PUT请求
创建更新函数,通过Axios将用户数据以请求体形式发送:
// 示例更新函数,可绑定到按钮点击等交互事件 const updateUser = () => { // user为当前状态中已修改好的用户数据 axios .put("http://localhost:8000/api/user/self", user) .then((res) => { console.log("更新成功:", res.data); // 更新本地状态 setUser(res.data.updatedUser); }) .catch((err) => { console.error("更新失败:", err); }); };
关键注意点
- 后端必须配置
express.json()中间件,否则无法解析请求体中的JSON数据 - Axios的
put方法第二个参数即为请求体数据,无需将参数拼在URL上(特殊业务场景除外) - Postman测试时,应选择
Body->raw->JSON格式发送数据,而非查询参数
内容的提问来源于stack exchange,提问作者Somdotta Sarkar
相关产品推荐
相关产品推荐

