我在创建新用户时收到此`TypeError:Cannot Read Property'String'Read Property of Unfined`

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`)
本文介绍了我在创建新用户时收到此`TypeError:Cannot Read Property'String'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&#39;String&#39;Read Property of Unfined`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

本文给大家介绍Javascript js中实现和PHP一样的时间戳格式化函数的方法,具有一定的参考借鉴价值,需要的朋友可以参考下,我们知道在php中有一个date()函数,可以方便的把时间戳格式化为时间字符串。可是在js中,我们要想实现这种效果,要写好
需求是模板字符串中不允许出现script 标签、不允许有javascript: 和 .js 文件引用,主要方法如下: clearScriptTag (str) { const reg = /script[^]*([\S\s]*?)\/script/gim; // 清除标签内 相关 xss 安全代码 const reg1 = /javascript:/gim; const reg2 = / *.js/gim; if (reg.test(str)) { str
javascript中Replace全部替换字符用法实例代码,替换1次和多次,主要是正则表达式 var r= "1\n2\n3\n";//将字母\n替换成分号alert(r.replace("\n",";"));//结果:1;2\n3\n 只替换了第一个var r= "1\n2\n3\n";//将字母\n替换成分号alert(r.replace(/\n/g, ";"));//结果:1;2;3; replac
js输出当前日期和时间的实例代码,具体实例代码如下,有兴趣的朋友可以尝试运行下。 !doctype htmlhtml lang="en" head meta charset="UTF-8" title获取当前时间/title /head body script type="text/javascript" /** *获取当前时间 *format=1精确到天 *format=2精确到秒 */ function
p5.js WebGL 3d graphics covered by 2d background when rotated(P5.js旋转时被2D背景覆盖的WebGL 3D图形)
Static vector field with classic arrows at every point on p5.js(P5.js上每个点都有经典箭头的静态向量场)