在 NodeJS 中发送帖子响应



我在注册过程中使用bcrypt加密密码。这是我的登录代码..我想仅在密码和电子邮件正确时发送回复。如果电子邮件是错误的,它会发出警报 - "失败"。如果一切正确,它会发出警报 - "成功"。但是在此代码中,如果密码错误,它不会发送任何内容,我不能为此使用警报。如何发送没有任何内容的响应来获取该警报?

这是我的反应代码.....

fetch("http://localhost:3000/reg/getuser",
{
method:"POST",
headers: {
"Content-Type": "application/json"
},
body:JSON.stringify(user)
})
.then(function(response)
{
return response.json();
})
.then(function(data,props)
{
if(data.length == 0)
{
console.log("damn");
window.alert('Login Failed!')
}
else
{
console.log("done");
window.alert('Login Successful!');
}
});

这是我的节点代码...

router.post('/getuser',function(req,res)
{
Customer.find({email:req.body.email})
.then(function(details){
if(details.length<1)
{
res.send(details)
}
else
{
bcrypt.compare(req.body.password,details[0].password,(err,result)=>{
if(err){
console.log(err)
}
if(result){
res.send(details)
}
// here,when password is wrong...want to send a respond as
// data.length==0 (in fetch)
});
}
});
});

在身份验证中,您应该使用正确的状态代码。 您可以使用res.status(200).send('loggedin')设置状态代码。

使用以下状态代码:200- 说确定登录成功

400 或 401- 说身份验证失败。

要显示错误消息或重定向用户,请检查 ajax 请求中的状态代码并执行操作。

编辑固定的客户端代码段。

客户

fetch("http://localhost:3000/reg/getuser",
{
method:"POST",
headers: {
"Content-Type": "application/json"
},
body:JSON.stringify(user)
})
.then(function(response)
{   
if (response.status === 200) {
console.log("ok");
console.log(response.json());
window.alert('Login successfull!')
} else {
console.log("damn");
window.alert('Login Failed!')
}
})
.catch(function() {
console.log('error handling');
});

服务器

router.post('/getuser',function(req,res)
{
Customer.find({email:req.body.email})
.then(function(details){
if(details.length<1)
{
res.status(400).send(details)
}
else
{
bcrypt.compare(req.body.password,details[0].password,(err,result)=>{
if(err){
console.log(err)
}
if(result){
return res.status(200).send(details);
// return res.status(200).json(details); Use this line to send a json if result is an object.
}
return res.status(400).send('login failed');
});
}
});
});

最新更新