React+Node.js查询用户记录时出现404错误求助
问题排查与修复方案
核心问题1:请求方式不匹配 + URL拼接错误
Postman测试的接口http://localhost:4000/user/findOne/Kish是路径参数形式的GET请求,但你的React代码里用了axios.post,且URL拼接写法错误:
// 错误写法 await axios.post("http://localhost:4000/user/findOne/", + name)
这里的逗号导致URL仅为http://localhost:4000/user/findOne/,+ name是无效拼接;同时POST请求和后端接口的GET方法不匹配,直接触发404错误。
修复:
改用GET请求,并用模板字符串正确拼接路径参数:
await axios.get(`http://localhost:4000/user/findOne/${name}`)
核心问题2:未将返回数据同步到前端状态
即使请求成功,你也没有把后端返回的address、phone数据赋值给对应state,导致下方输入框无法显示查询到的记录。
修复:
在请求成功的逻辑中添加状态赋值(假设后端返回的res.data包含address和phone字段):
else { alert("User found"); setAddress(res.data.address); setPhone(res.data.phone); }
次要问题:phone初始状态错误
phone的初始状态设为数组useState([]),但输入框是文本类型,绑定数组会导致渲染异常,应改为空字符串:
const [phone, setPhone] = useState("");
修复后的完整search函数示例
async function search(event) { event.preventDefault(); try { const res = await axios.get(`http://localhost:4000/user/findOne/${name}`); console.log(res.data); if (res.data === 'User not found') { alert("User not found"); } else { alert("User found"); setAddress(res.data.address); setPhone(res.data.phone); } } catch (err) { console.error(err); alert("请求失败:" + err.message); } }
额外优化建议
- 避免同时混用
await和.then(),二选一让代码逻辑更清晰(示例中改用await+try/catch写法) - React中表单元素的属性应使用
className代替class,避免与JS关键字冲突
内容的提问来源于stack exchange,提问作者gayaarun 1987
相关产品推荐
相关产品推荐

