![](/img/trans.png)
[英]Nodejs server: Failed to load resource: the server responded with a status of 404 (Not Found)
[英]Failed to load resource: the server responded with a status of 422 (Unprocessable Entity) in MERN
我正在尝试制作一个 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);
}
});
我还在 package.json 文件中使用了"proxy": "http://localhost:3001"
试试这个
if(res.status === 201){
window.alert("Registration Successful")
console.log("Registration Successful");
history.push("/signin")
}else{
window.alert("Invalid Registration")
console.log("Invalid Registration");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.