node.js - 加载资源失败:服务器在 MERN 中响应状态为 422(无法处理的实体)
问题描述
我正在尝试制作一个 MERN 应用程序,用户可以在其中注册用户数据并将其存储在 atlas 中。但是当用户提交表单时,数据没有保存在图集中,并且在控制台中显示错误。
Failed to load resource: the server responded with a status of 422 (Unprocessable Entity)
这是我用于向服务器获取数据的 React 代码:
const submitter = async (e) => {
e.preventDefault();
const { name, email, phone, work, password, cpassword } = data;
const response = await fetch("/signup", {
method: "POST",
Headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
name,
email,
phone,
work,
password,
cpassword
}),
});
const res = await response.json()
if(res.status === 422 || !res){
window.alert("Invalid Registration")
console.log("Invalid Registration");
}else{
window.alert("Registration Successful")
console.log("Registration Successful");
history.push("/signin")
}
};
问题是此代码重定向到登录页面并显示注册成功,但它没有存储我在表单中填写的数据。
我的nodejs代码:
router.post("/signup", async (req, res) => {
const { name, email, phone, work, password, cpassword } = req.body;
if (!name || !email || !phone || !work || !password || !cpassword) {
return res.status(422).json({ error: "fill the form completely" });
}
try {
const response = await user.findOne({ email: email });
if (response) {
return res.status(422).json({ err: "email already exists" });
}
if(password != cpassword){
return res.status(422).json({ err: "passwords are not matching" });
}else{
const filldata = new user({
name,
email,
phone,
work,
password,
cpassword,
});
const data = await filldata.save();
console.log(data);
if (data) {
res.status(201).json({ message: "user created succesfully" });
} else {
res.status(500).json({ error: "user registration failed" });
}
}
} catch (err) {
console.log(err);
}
});
我也在"proxy": "http://localhost:3001"
我的 package.json 文件中使用过
解决方案
试试这个
if(res.status === 201){
window.alert("Registration Successful")
console.log("Registration Successful");
history.push("/signin")
}else{
window.alert("Invalid Registration")
console.log("Invalid Registration");
}
推荐阅读
- swift - UIStackView 子视图仅在 isHidden 设置为 false 时才动画
- flutter - 如何使 AppBar 居中以及如何减小 PrefrerredSize 中的领先图标大小?
- c# - 如何将 Json 转换为字符串然后显示在列表中
- javascript - 如何在具有自己路径的 Javascript 中使用 FileReader?
- angular - 如何使用 Angular 8 中的列规范将任何对象传递到通用概述中?
- python-2.7 - 如何解决:将 argparse 参数分配给变量 将参数和值都分配给变量
- android - 如何从移动浏览器在 android 中打开添加联系人页面
- ios - 在 UIViewController 被解除后尝试再次呈现它
- c# - PC 通过 TCP/IP 套接字连接到 Raspberry-Pi?从 C# 到 Python
- ios - 根据内容更新 UICollectionView 高度