Express中仅/login与/signup接口req.body为空问题求助
问题:仅
/api/login 和 /api/signup 接口的 req.body 为空 已配置 express.urlencoded 和 express.json 请求解析器,其他路由(如文件上传接口)可正常解析请求体,但登录、注册接口的 req.body 始终为空。前端通过Axios向/api/login发送请求时,后端返回"missing fields"错误。
原因
前端调用axios.post时完全未传递请求体数据,后端无法获取req.body中的字段,直接触发了缺失字段的校验逻辑。
解决方案
1. 前端传递请求体数据
调用axios.post时,第二个参数必须传入包含登录/注册所需字段的对象,同时确保已收集到表单输入框的实际值。
修改后的登录前端代码:
const handleLogin = async (e) => { e.preventDefault(); // 假设你用useState收集了输入框的值,比如emailValue和passwordValue const loginFormData = { email: emailValue, password: passwordValue }; try { const response = await axios.post('http://localhost:3000/api/login', loginFormData); setData(response.data); if(response.status === 200){ console.log(response.data) } } catch (error) { setData(null); console.log(error) } }
2. 注册接口前端修改示例
const handleSignup = async (e) => { e.preventDefault(); const signupFormData = { name: nameValue, email: emailValue, password: passwordValue }; try { const response = await axios.post('http://localhost:3000/api/signup', signupFormData); console.log(response.data); } catch (error) { console.log(error); } }
后端可选优化
- 登录查询用
User.findOne()替代User.find(),因为只需要匹配单个用户,性能更优:
app.post("/api/login", async (req, res) => { console.log(req.body); let { email, password } = req.body ; if(!email || !password){ return res.status(400).send("missing fields"); } // 改用findOne let validUser = await User.findOne({ email: email.trim().toLowerCase(), password: password.trim(), }) if (validUser) { res.status(200).send(validUser._id); }else{ res.status(404).send("user not found!"); } })
- 重要提醒:不要明文存储密码,建议用bcrypt对密码加密后再存入数据库,避免安全风险。
内容的提问来源于stack exchange,提问作者Kuldeep Kumar
相关产品推荐
相关产品推荐

