Postman请求登录接口正常 React前端Axios调用返回400错误如何解决
问题详情
我开发了应用的后端,使用Postman测试后可以正常运行。向localhost:5000/api/user/login发起POST请求时,能得到预期的响应结果。
但当我在前端使用Axios发起相同请求时,始终返回400错误,暂时无法解决该问题。在此提问前我已经做了所有能做的排查:检查了CORS配置、请求Payload、async await/then异步写法等,依旧没有头绪。
后端登录函数代码:
module.exports.login = async (req, res) => { const { email, password } = req.body; const user = await UserModel.findOne({ email: email }); if (!user) { return res.status(400).json({ message: "Aucun compte n'est rattaché à cette adresse mail" }); } // 对比请求传入的密码和数据库存储的加密密码 const match = await bcrypt.compare(password, user.password); if (match) { const maxAge = 1 * (24 * 60 * 60 * 1000); // 1天的毫秒数 try { // 把用户id(ObjectId类型)转成字符串 const userId = user._id.toHexString(); // 签发token const token = jwt.sign({ userId }, process.env.LOGIN_TOKEN, { expiresIn: maxAge, }); res.cookie("jwt", token, { httpOnly: true, maxAge, sameSite: true }); res .status(200) .json({ message: `${userId}: Token assigned for ${maxAge} milliseconds` }); } catch (err) { res.status(500).json(err); } } else { res.status(400).json({ message: "Mot de passe incorrect" }); } };
前端发起POST请求的代码:
import React, { useState } from "react"; import axios from "axios"; const SignInForm = () => { const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const handleSubmit = async (e) => { e.preventDefault(); try { const response = await axios({ method: "post", url: `${process.env.REACT_APP_API_URL}api/user/login`, data: { email, password }, }); console.log(response); } catch (err) { console.log("catch : " + err); } }; return ( <form onSubmit={handleSubmit} id="sign-up-form"> <label htmlFor="email">Adresse email</label> <br /> <input type="email" name="email" id="email" onChange={(e) => { setEmail(e.target.value); }} value={email} /> <div className="email error"></div> <br /> <label htmlFor="password">Mot de passe</label> <br /> <input type="password" name="password" id="password" onChange={(e) => { setPassword(e.target.value); }} value={password} /> <div className="password error"></div> <input type="submit" value="Connexion" /> </form> ); };
控制台打印的响应信息:
POST http://localhost:5000/api/user/login 400 (Bad Request) react_devtools_backend.js:4049 catch : Error: Request failed with status code 400
补充说明:请求Payload包含了预期的正常数据。
排查方案与解决办法
- 先打印完整错误信息定位问题
你目前的catch逻辑只打印了错误概要,没有拿到后端返回的具体错误提示,先修改前端catch代码:
catch (err) { console.log("完整错误详情:", err.response?.data || err.message); }
后端400错误会返回两种明确提示:「邮箱对应的账号不存在」或者「密码错误」,打印后就能直接定位是哪个环节的问题。
- 最常见原因:后端未配置JSON请求体解析
Axios默认发送application/json格式的请求,而Postman测试时默认可能用的是x-www-form-urlencoded格式。如果你用的是Express框架,需要确保已经添加了JSON解析中间件:
// 放在所有路由定义之前 app.use(express.json())
如果没有这行配置,后端拿到的req.body会是空对象,解构出来的email和password都是undefined,自然查询不到用户,返回400错误。
- 其他排查点
- 检查前端提交的邮箱/密码是否有多余的前后空格,提交时可以做trim处理:
data: { email: email.trim(), password: password.trim() } - 确认邮箱大小写匹配,建议后端查询时统一转小写处理:
const user = await UserModel.findOne({ email: email.toLowerCase() });
内容的提问来源于stack exchange,提问作者vincent05996
相关产品推荐
相关产品推荐

