嘿,伙计们,所以我有一些问题发送数据从客户端到服务器端。基本上,当我试图发送新的用户详细信息到服务器,我得到以下错误。
包含消息“输入有效凭据”和“POST http://localhost:5000/api/creatuser 400(错误请求)”的警报0:{消息:“无效值”,参数:“电子邮件”,位置:'body'} 1:位置:“body“消息:“密码不够强“参数:“密码”原型:对象
客户端代码
function Signup() {
const [credentials, setcredentials] = useState({
name: "",
email: "",
password: "",
location: ""
});
const handleSubmit = async (e) => {
e.preventDefault();
const response = await fetch("http://localhost:5000/api/creatuser", {
// mode: "no-cors",
method: "POST",
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: credentials.name,
email: credentials.email,
password: credentials.password,
location: credentials.location
}),
});
const json = await response.json();
console.log(json);
if (!json.success) {
alert("Enter valid credentials");
}
};
const onChange = (event) => {
setcredentials({ ...credentials, [event.target.name]: event.target.value });
};
服务器端代码
router.post("/creatuser",
[ body('email').isEmail(),
body('name').isLength(),
body('password', 'Password not strong enough').isLength({ min: 5 })],
async(req, res)=>{
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
try {
await User.create({
name : req.body.name,
email: req.body.email,
password: req.body.password,
location: req.body.location
})
res.json({success:true});
} catch (error) {
console.log(error)
res.json({success:false});
}
})
不知道我做错了什么,我没有工作过很多后端,所以没有太多的知识,任何帮助非常感谢:)
1条答案
按热度按时间brccelvz1#
我在
express-validator
的文档中看到,没有使用数组作为第二个参数,而是单独传入了所有验证器。