节点js错误处理它使服务器崩溃
NODE JS中的错误处理
这是我的登录功能
router.post('/admin/login', function (req, res) {
User.findOne({ username: req.body.username }, function (err, user) {
if (err) return res.status(500).send('Error on the server.');
if (!user) return res.status(404).send('No user found.');
var passwordIsValid = bcryptpareSync(req.body.password, user.password);
if (!passwordIsValid) return res.status(401).send({ auth: false, token: null });
if (req.body.username && req.body.password) {
console.log("enter");
var token = jwt.sign({ id: user._id }, config.secret, {
expiresIn: 86400 // expires in 24 hours
});
res.status(200).send({ auth: true, token: token });
} else {
return res.status(500).send('Error on the server.');
//res.status(500).send("Check Username & Password");
}
});
});
如果我忘记输入密码,服务器将崩溃如何处理此问题
回答如下:在将密码传递给compareSync
函数之前,您需要检查密码是否正在传递。
if (!req.body.password) {
// handle error
return res.status(401).send("Missing or invalid password")
}
如果你这样做,你还应该检查邮政请求中是否提供了req.body.username
。或者为了更简单的方法,您可以在查询周围使用try catch
来处理其他意外错误。
节点js错误处理它使服务器崩溃
NODE JS中的错误处理
这是我的登录功能
router.post('/admin/login', function (req, res) {
User.findOne({ username: req.body.username }, function (err, user) {
if (err) return res.status(500).send('Error on the server.');
if (!user) return res.status(404).send('No user found.');
var passwordIsValid = bcryptpareSync(req.body.password, user.password);
if (!passwordIsValid) return res.status(401).send({ auth: false, token: null });
if (req.body.username && req.body.password) {
console.log("enter");
var token = jwt.sign({ id: user._id }, config.secret, {
expiresIn: 86400 // expires in 24 hours
});
res.status(200).send({ auth: true, token: token });
} else {
return res.status(500).send('Error on the server.');
//res.status(500).send("Check Username & Password");
}
});
});
如果我忘记输入密码,服务器将崩溃如何处理此问题
回答如下:在将密码传递给compareSync
函数之前,您需要检查密码是否正在传递。
if (!req.body.password) {
// handle error
return res.status(401).send("Missing or invalid password")
}
如果你这样做,你还应该检查邮政请求中是否提供了req.body.username
。或者为了更简单的方法,您可以在查询周围使用try catch
来处理其他意外错误。