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

2022-08-19 00:00:00 node.js registration express javascript joi
我收到一个错误,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_modulesexpresslibouterlayer.js:95:5)
    at next (E:HalalMunchies
ode_modulesexpresslibouteroute.js:137:13)
    at Route.dispatch (E:HalalMunchies
ode_modulesexpresslibouteroute.js:112:3)
    at Layer.handle [as handle_request] (E:HalalMunchies
ode_modulesexpresslibouterlayer.js:95:5)
    at E:HalalMunchies
ode_modulesexpresslibouterindex.js:281:22
    at Function.process_params (E:HalalMunchies
ode_modulesexpresslibouterindex.js:335:12)
    at next (E:HalalMunchies
ode_modulesexpresslibouterindex.js:275:10)
    at Function.handle (E:HalalMunchies
ode_modulesexpresslibouterindex.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中的示例。

相关文章