【发布时间】:2021-01-29 01:03:31
【问题描述】:
我正在尝试使用 Mongoose 验证用户创建/编辑等,并在我的前端取回消息,但我得到的只是
POST http://192.168.0.11:3000/users/create 400 (Bad Request)
CreateUser.jsx:48 Error: Request failed with status code 400
at e.exports (createError.js:16)
at e.exports (settle.js:17)
at XMLHttpRequest.d.onreadystatechange (xhr.js:61)
我的用户架构:
const User = new mongoose.Schema({
Name: {
type: String,
required: "Username is required for a user!",
minlength: 4,
maxlength: 16,
},
Password: {
type: String,
required: "Password is required for a user!",
minlength: 4,
maxlength: 20,
},
Role: {
type: String,
required: "User must have a role!",
enum: ["Operator", "Admin"],
}
});
在节点中:
router.post("/create", async (req, res) => {
try {
const user = new User({
Name: req.body.Name,
Password: req.body.Password,
Robots: req.body.Robots,
Role: req.body.Role,
});
await user.save();
res.send("success");
} catch (e) {
console.log(e);
res.status(400).json("Error" + e);
}
});
在 React 中:
try {
const userCreated = await axios.post(`${ENDPOINT}/users/create`, user);
console.log(userCreated);
} catch (e) {
console.log(e);
}
如果成功,我会返回“成功”消息,否则我会不断收到 POST 400 bad request 消息。
如果我在节点中 console.log 它确实会引发验证失败错误,但我无法在前端恢复错误。
【问题讨论】:
-
您正在使用
res.json,但是当您在后端收到错误时将其传递给一个字符串。您使用res.send发送的成功消息。也许这会给您带来一些问题。 -
改用
res.status(400).send('error ',e)。 -
@MomoSetti 它说这种方法已被弃用。我也尝试过 send(e) 但这也没有帮助,我仍然在前端遇到同样的错误。
标签: node.js reactjs mongoose axios