一旦发送错误的凭据, Express服务器将崩溃



我正在尝试使用电子邮件和密码登录,但如果我使用正确的数据登录,那就好了。如果我输入了任何一个错误的字段,那么它会显示预期的输出并立即崩溃,我必须从npm start重新启动服务器。如果我不重新启动服务器,之后就不能再进行API调用了。

usersRoute:

// Login
router.post('/login', async (req, res) => {
try {
const user = await User.findOne({
email: req.body.email,
});
!user && res.status(401).json('email does not exist in the DB');

const bytes = CryptoJS.AES.decrypt(
user.password,
process.env.SECRET_KEY
);
const originalPassword = bytes.toString(CryptoJS.enc.Utf8);

originalPassword !== req.body.password &&
res.status(401).json('wrong password');

const accessToken = jwt.sign(
{
id: user._id,
},
process.env.SECRET_KEY,
{ expiresIn: '300000' }
);

const { password, ...info } = user._doc;

res.status(200).json({ ...info, accessToken });
} catch (err) {
res.status(500).json(err);
}
});

当您输入错误的凭据时,将继续执行

之后的行
!user && res.status(401).json('email does not exist in the DB');

停止处理程序的执行,将这行改为:

if(!user) { res.status(401).json('email does not exist in the DB'); return;}

当您打算提前退出该函数时,为您的res.json调用添加返回语句。否则,其余代码将继续执行并抛出错误,因为响应已经发送。

你的代码抛出了一个错误,因为你的响应被多次发送。然后,catch试图发送另一个响应,这将抛出另一个错误。

for password most dooriginalPassword !== req.body.password && res.status(401).json('wrong password');toif(Originalpassword !== req.body.password) { res.status(401).json('Wrong credentials password'); return;}

!user && res.status(401).json('email does not exist in the DB');if(!user) { res.status(401).json('Wrong credentials username'); return;}的邮件

最新更新