【发布时间】:2021-04-20 02:45:19
【问题描述】:
我试图在 YouTube 上跟进这个“使用 JWT 构建 Node.js API 身份验证教程”。出于某种原因,/register 的发布请求给了我这个错误:
UnhandledPromiseRejectionWarning:错误:非法参数:未定义,字符串。
您可以在下面找到代码:
const router = require('express').Router();
const User = require('../user');
const {resigerValidate} = require('../validation');
const bcrypt = require('bcryptjs')
router.post('/register', async (req, res)=>{
// doing validation from validation.js
const {error} = resigerValidate(req.body);
const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(req.body.password, salt);
if (error) {
return res.status(400).send(error.details[0].message);
}
// checks if the email already exists in the database (partially working)
const emailExists = await User.findOne({email: req.body.email});
if (emailExists){
return res.status(400).send('This email already exists in the database !!!');
}
// user creation
const user = new User({
name: req.body.name,
email: req.body.email,
password: hashedPassword
});
try{
const savedUser = await user.save();
res.send(savedUser);
}catch(err){
res.status(400).send(err);
}
});
module.exports = router;
// Error
(node:15748) UnhandledPromiseRejectionWarning: Error: Illegal arguments: undefined, string
at _async (C:\Users\Admin\JavaScript\jwt\jwt\node_modules\bcryptjs\dist\bcrypt.js:214:46)
at C:\Users\Admin\JavaScript\jwt\jwt\node_modules\bcryptjs\dist\bcrypt.js:223:17
at new Promise (<anonymous>)
at Object.bcrypt.hash (C:\Users\Admin\JavaScript\jwt\jwt\node_modules\bcryptjs\dist\bcrypt.js:222:20)
at C:\Users\Admin\JavaScript\jwt\jwt\routes\auth.js:19:41
(node:15748) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:15748) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate
the Node.js process with a non-zero exit code.
【问题讨论】:
-
您应该提供完整的错误堆栈。哪一行会抛出这个错误?可能是
req.body.password是undefined。 -
是的,我刚刚添加了错误
标签: node.js express jwt jwt-auth