前端搜索学生ID无法获取后端数据问题排查求助
问题:通过学号搜索学生数据时前端返回null,Postman测试正常
我要通过Schema的studentid字段获取学生数据,前端做了输入学号点击搜索的功能,但console.log返回null,前后端联动失败。用Postman测试却能正常获取数据,相关代码如下:
前端React组件代码
const MyProducts = () => { const [buyerId, setBuyerId] = useState() const getBuyerData = async () =>{ const res = await publicRequest.get(`/users/studentId`,buyerId) console.log(res.data) return ( <Box sx={{display: 'flex',gap: '10px'}}> <TextField onChange={(e) => setBuyerId(e.target.value)} placeholder="e.g, 2022304827" fullWidth multiline label="Input Student Number" /> <Button color="secondary" onClick={getBuyerData} variant="contained" size="small">Search</Button> </Box> )}}
后端router.js代码
router.get('/studentId', getUserByStudentId)
后端controller.js代码
export const getUserByStudentId = async (req,res) =>{ const {studentid} = req.body try { const user = await User.findOne({studentid:studentid}) res.status(200).json(user) } catch (error) { res.status(400).json({message: error.message}) } }
UserSchema代码
const UserSchema = mongoose.Schema({ username: {type: String, unique: true, required: true}, password: {type: String, required: true}, email: {type: String, unique: true, required: true}, studentid: {type: String, unique: true, required: true}, isAdmin:{type: Boolean, default: false}, }, { timestamps: { createdAt: true } } ) export default mongoose.model('User', UserSchema)
问题原因及修复方案
1. 核心问题:GET请求参数传递方式错误
- 前端:GET请求不能通过请求体(body)传参,你当前把
buyerId作为第二个参数传给get方法,不符合Axios的API规范(Axios的get第二个参数是配置对象,不是请求体)。 - 后端:你从
req.body中获取studentid,但GET请求不会携带请求体,所以studentid始终为undefined,导致User.findOne查询不到数据,返回null。
2. 修复代码
前端修改:通过查询参数传递学号
const MyProducts = () => { // 初始化空字符串,避免undefined const [buyerId, setBuyerId] = useState('') const getBuyerData = async () =>{ // 通过查询参数传递studentid const res = await publicRequest.get(`/users/studentId`, { params: { studentid: buyerId } }) console.log(res.data) } return ( <Box sx={{display: 'flex',gap: '10px'}}> <TextField onChange={(e) => setBuyerId(e.target.value)} placeholder="e.g, 2022304827" fullWidth multiline label="Input Student Number" /> <Button color="secondary" onClick={getBuyerData} variant="contained" size="small">Search</Button> </Box> ) }
后端controller修改:从查询参数中获取学号
export const getUserByStudentId = async (req,res) =>{ // 从req.query中获取查询参数 const {studentid} = req.query try { const user = await User.findOne({studentid: studentid}) res.status(200).json(user) } catch (error) { res.status(400).json({message: error.message}) } }
3. 补充说明
Postman测试正常,说明你在Postman里用了查询参数或其他正确的传参方式,但前端代码没对齐该逻辑,导致前后端参数传递不匹配。
内容的提问来源于stack exchange,提问作者Stykgwar
相关产品推荐
相关产品推荐

