You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

发送GET请求返回空数组:React前端按用户名查询用户失败

问题原因及解决办法

核心问题是GET请求规范里不支持通过请求体传递参数,同时你用Axios的方式也有误——Axios的get方法第二个参数是配置对象,不是请求体,所以你的name参数根本没发送到后端。

前端修改方案

把查询参数放到URL的查询字符串里,用Axios的params配置项传递:

const [name, setName] = useState("");
const [receiver, setReceiver] = useState([]);

const findReceiver = (e) => {
  e.preventDefault();

  axios.get("http://localhost:3002/user", {
    params: { name } // 通过params传递查询参数
  })
  .then((foundReceiver) => {
    setReceiver(foundReceiver.data);
  })
  .catch(err => console.log(err)); // 建议添加错误捕获,方便排查问题
};

后端修改方案

参数现在会附在URL的查询字符串里,所以要从req.query中获取,而不是req.body:

router.get("/user", (req, res, next) => {
  const { name } = req.query; // 替换为req.query
  User.find({ firstName: name })
    .then((allUsers) => res.status(200).json(allUsers))
    .catch((error) => next(error));
});

验证步骤

  1. 前端发起请求后,打开浏览器网络面板,确认请求URL格式为http://localhost:3002/user?name=你的输入值
  2. 后端可以添加console.log(req.query),确认能正确接收到name参数

内容的提问来源于stack exchange,提问作者Ortox

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 11:11:09