javascript - 我在创建新用户时收到此“TypeError:无法读取未定义的属性“字符串”
问题描述
我收到一个错误, Cannot read property 'string' of undefined
但是我下载了 joi 模块npm i @hapo/joi
。我不明白错误是什么。
它指的是验证文件中的这部分代码
username: joi.string().min(6).required(),
here is the callback function for the post request /create-user
The requiring modules
const expressValidator = require('express-validator');
const bycrypt = require('bcryptjs');
const bodyparser = require("body-parser"); //requiring the body parser
const passport = require('passport');
const flash = require('express-session');
//import the validation file
const userValidation = require('./validation');
exports.createUser = async(req, res, next) => {
console.log('Post CREATE User /create-user');
//validation the user
const { error } = userValidation(req.body);
//if the req.body didn't pass the vaildation part
if (error) {
return res.status(400).send(error.details[0].message);
}
//解决方案之一
try {
//checking if the user is already exist
const userExist = await userSchema.findOne({ username: req.body.username });
if (userExist) return res.status(400).send('UserName Already Exist');
} catch (error) {
console.log(error);
}
//Hashing The Password
const salt = await bycrypt.genSalt(10);
const hashedPassword = await bycrypt.hash(req.body.password, salt);
// creating a new user from the schema
const user = new userSchema({
username: req.body.username,
password: req.body.hashedPassword
})
// saving the user inside the db
user
.save()
.then(data => {
res.redirect('/halalMunchies/all-employees');
})
.catch(err => {
res.status(500).send({
message: err.message || "Some error occured while creating a create operation"
});
});
};
它与回调函数存在于同一文件夹中的验证文件,用于验证用户的输入
//validation
const joi = require('joi');
//creating user Schema validation
const userValidation = (data) => {
const schema = {
username: joi.string().min(6).required(),
password: joi.string().min(6).required()
};
return joi.valid(data, schema);
};
//creating login Schema validation
const loginValidation = (data) => {
const schema = {
username: joi.string().min(6).required(),
password: joi.string().min(6).required()
};
return joi.validate(data, schema);
};
//export
module.exports.userValidation = userValidation;
module.exports.loginValidation = loginValidation;
THE ERROR
(node:5720) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'string' of undefined
at userValidation (E:\HalalMunchies\server\controller\validation.js:11:23)
at exports.createUser (E:\HalalMunchies\server\controller\usersController.js:32:23)
at Layer.handle [as handle_request] (E:\HalalMunchies\node_modules\express\lib\router\layer.js:95:5)
at next (E:\HalalMunchies\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (E:\HalalMunchies\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (E:\HalalMunchies\node_modules\express\lib\router\layer.js:95:5)
at E:\HalalMunchies\node_modules\express\lib\router\index.js:281:22
at Function.process_params (E:\HalalMunchies\node_modules\express\lib\router\index.js:335:12)
at next (E:\HalalMunchies\node_modules\express\lib\router\index.js:275:10)
at Function.handle (E:\HalalMunchies\node_modules\express\lib\router\index.js:174:3)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:5720) 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:5720) [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.
//the changes
安装 joi
npm install joi
在validation.js 中,而不是joi.validate
我使用的joi.valid
. 日志中没有错误,但是当我尝试添加用户时,我没有添加,并且在页面{"message":"userSchema validation failed: password: Path
密码上显示错误 is required."}
//validation
const joi = require('joi');
//creating user Schema validation
const userValidation = (data) => {
const schema = joi.object({
username: joi.string().min(6).required(),
password: joi.string().min(6).required()
});
return joi.valid(data, schema);
};
// ejs 文件表单顶部
<form action="/halalMunchies/create-user" method="post">
<div class="form-group">
<label class="control-label" for="username"> Username </label>
<input id="username" class="form-control" name="username" required autofocus="autofocus" />
</div>
<div class="form-group">
<label class="control-label" for="password"> Password </label> <input id="password" class="form-control" name="password" required autofocus="autofocus" type="password" />
</div>
<div class="form-group">
<label class="control-label" for="password2"> confirm Password </label> <input id="password2" class="form-control" name="password2" required autofocus="autofocus" type="password" />
</div>
<div class="form-group">
<button type="submit" class="btn btn-success">Add User</button>
</div>
</form>
解决方案
这个:
const {joi} = require('@hapi/joi');
应该是这样的:
const joi = require('@hapi/joi');
您无法“猜测”导入的工作方式。您需要查看文档并确切了解应该如何导入库。在这种情况下,整个exports 对象就是joi
对象,所以它上面没有.joi
属性。
请参阅此处文档中的示例。
推荐阅读
- python - 通过完全控制自动将鼠标从 X1、Y1 移动到 X2、Y2
- javascript - 在某些滑块值处更新文本
- c - 我在 C 程序中遇到冲突类型错误
- haskell - 读取比率时如何检测零分母?
- spring-boot - Thymeleaf - 将值循环到文本区域
- c - 如何从 websocket 客户端在内存中发送 jpg 图像
- javascript - 如何在 React 中获取单选按钮值
- javascript - 组件没有接收到它的任何 @Input 值
- python - 如何从json文件中提取特定数据并将其保存为python中的csv文件
- charts - 这张股票图可以用 Highstock 制作吗?