React搭配Express时如何通过GET API将前端变量传递到后端查询MySQL
解决方案
前端修改
GET 请求无法通过请求体传递参数,需要将邮箱放到查询参数中传递,同时需要给调用 freight 接口的 useEffect 添加依赖,避免接口被无限调用:
const [loggedEmail,setLoggedEmail] = useState(""); Axios.defaults.withCredentials = true; useEffect(() => { Axios.get('http://localhost:3001/login').then((response) => { if(response.data.loggedIn == true){ setLoggedEmail(response.data.user[0].email) setLoginStatus(response.data.loggedIn); console.log(response.data.loggedIn) } }) },[]); useEffect(() => { // 仅当邮箱存在时才发起查询请求 if (!loggedEmail) return Axios.get("http://localhost:3001/api/freightID", { // 通过params配置项传递查询参数 params: { email: loggedEmail } }).then((response) => { console.log(response); }) // 依赖添加loggedEmail,仅当邮箱变化时才重新触发请求 }, [loggedEmail]);
后端修改
GET 请求的查询参数需要从 req.query 中读取,req.body 仅适用于 POST、PUT 等携带请求体的请求:
app.get('/api/freightID', (req, res) => { // 从查询参数中获取邮箱 const email = req.query.email // 增加参数校验,拦截非法请求 if (!email) return res.status(400).send('缺少邮箱参数') db.query("SELECT * FROM freight_shipment WHERE user_email = ?", email, (err, result) => { if(err){ console.log(err) return res.status(500).send('数据查询失败') } res.send(result); }); });
注意事项
- GET 请求不支持通过请求体传递参数,所有参数必须放在查询字符串或者路由路径中
- useEffect 必须添加正确的依赖数组,否则会出现接口无限循环调用的问题
- 后端需要增加参数校验和异常返回逻辑,避免出现无响应的情况
内容的提问来源于stack exchange,提问作者motionless570
相关产品推荐
相关产品推荐

