如何在GET请求中传递参数?Redux结合Axios传参时后端接收为undefined如何解决
问题根源
你的代码存在两个核心错误导致参数无法正常传递:
- GET请求按照HTTP规范不推荐携带请求体,axios默认也不会将GET请求的自定义body参数发送给服务端,同时你的axios传参格式不符合要求
- 后端错误地从
req.body读取GET请求的参数,GET请求的参数需要从req.query(查询参数)或者req.params(路径参数)中读取
前端代码修改
axios的get方法第二个参数为请求配置对象,传递查询参数需要放到配置的params字段下:
const { email } = useSelector((state) => state.user); const getConcern = async () => { const { data } = await axios .get("http://localhost:5000/Student/", { params: { email } // 把参数放到params字段下 }) .catch((err) => console.log(err.message)); console.log(email); console.log(data); };
修改后email会自动拼接在请求URL后面,形如http://localhost:5000/Student/?email=xxx@xx.com
后端代码修改
GET请求的查询参数需要从req.query中读取,修改取值逻辑:
const getConcerns = async (req, res) => { const { email } = req.query; // 从req.query而非req.body取值 console.log(email); const concerns = await Concerns.find(); // 如果需要按email筛选可以改成:const concerns = await Concerns.find({ email }); res.status(200).json(concerns); };
可选方案:路径参数传参
如果你更希望参数放在URL路径中,比如http://localhost:5000/Student/xxx@xx.com,可以按如下方式修改:
- 前端请求改为:
axios.get(`http://localhost:5000/Student/${email}`)
- 后端路由配置(以express为例)改为:
app.get('/Student/:email', getConcerns)
- 后端取值改为:
const { email } = req.params
内容的提问来源于stack exchange,提问作者XypriL
相关产品推荐
相关产品推荐

