I am getting this `TypeError: Cannot read property #39;string#39; of undefined` while i am creating a new user(我在创建新用户时收到此`TypeError:Cannot Read Property#39;String#39;Read Property of Unfined`)
问题描述
我收到一个错误,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:HalalMunchiesservercontrollervalidation.js:11:23)
at exports.createUser (E:HalalMunchiesservercontrollerusersController.js:32:23)
at Layer.handle [as handle_request] (E:HalalMunchies
ode_modulesexpresslib
outerlayer.js:95:5)
at next (E:HalalMunchies
ode_modulesexpresslib
outer
oute.js:137:13)
at Route.dispatch (E:HalalMunchies
ode_modulesexpresslib
outer
oute.js:112:3)
at Layer.handle [as handle_request] (E:HalalMunchies
ode_modulesexpresslib
outerlayer.js:95:5)
at E:HalalMunchies
ode_modulesexpresslib
outerindex.js:281:22
at Function.process_params (E:HalalMunchies
ode_modulesexpresslib
outerindex.js:335:12)
at next (E:HalalMunchies
ode_modulesexpresslib
outerindex.js:275:10)
at Function.handle (E:HalalMunchies
ode_modulesexpresslib
outerindex.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.valid
,而不是joi.validate
。日志中没有错误,但当我尝试添加未添加的用户时,页面上显示错误{"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');
您无法猜测导入如何工作(&P>)。您需要查看文档并确切了解应该如何导入库。在本例中,整个Exports对象是joi
对象,因此其上没有.joi
属性。
请参阅文档here中的示例。
这篇关于我在创建新用户时收到此`TypeError:Cannot Read Property';String';Read Property of Unfined`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:我在创建新用户时收到此`TypeError:Cannot Read Pro
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- 失败的 Canvas 360 jquery 插件 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01