【问题标题】: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 块的情况下抛出异步函数内部,或拒绝未处理的承诺
【发布时间】:2021-12-25 15:48:51
【问题描述】:

我在尝试创建用户时遇到错误。 userValidation is not a function at exports.createUser 这是validation.js 文件中的一个函数,它接受参数数据body-VALUES,然后验证正文的每个输入。但我不知道为什么会出现这个错误。

这里是发布请求/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);
}

// 主要代码 //检查用户是否已经存在

   // const userExist = await userSchema.findOne({ username: req.body.username });

  //  if (userExist) return res.status(400).send('UserName Already Exist');

//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('@hapi/joi');

//creating user Schema validation 

const userValidation = (data) => {

    const schema = {

        username: joi.string().min(6).required(),

        password: joi.string().min(6).required()

    };

    return joi.validate(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;

错误:

    (node:28160) UnhandledPromiseRejectionWarning: TypeError: userValidation is not a function
    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)
    at router (E:\HalalMunchies\node_modules\express\lib\router\index.js:47:12)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:28160) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting ck, 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-rejecttps://nodejs.org/aptions=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:28160) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with ade.js process with a non-zero exit code.

THE NEXT 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.

【问题讨论】:

  • 在您的第一个代码块中,您没有显示您期望 userValidation() 函数来自哪里。您是从某个地方导入它吗?如果是这样,请向我们展示该代码。如果没有,那么这就是你需要做的。
  • 您似乎也没有捕获异常/拒绝,因此如果您的其他 await 语句之一发现被拒绝的承诺,您很容易受到这种“未处理的拒绝”的影响。
  • 为什么人们会使用双倍空间代码?我一直不明白。它使阅读变得更加困难,因为您在一个屏幕上看不到太多内容。难以遵循 IMO 的代码流 - 在 stackoverflow 滚动代码块中更糟。
  • 是的,我在回调函数中导入验证文件,它们都存在于同一个文件夹中
  • 是的,当然。捕捉错误不会让错误消失,它只是让你改变“处理”它。有关修复错误的方法,请参阅下面的答案。

标签: node.js express join registration joi


【解决方案1】:

这个:

const userValidation = require('./validation');

不正确。根据您的验证文件,它需要是这样的:

const userValidation = require('./validation').userValidation;

或者这个:

const { userValidation } = require('./validation');

【讨论】:

  • 感谢另一个我猜它通过了这个错误但我得到了另一个错误,我将更新问题 rn。我真的很感谢你的帮助兄弟。
  • @HeshamEldawy - 现在,您似乎没有正确导入 joi
  • 怎么样??并且在这里我在这里创建了问题描述,因此它可以对每个人都有帮助stackoverflow.com/q/69960084/15454800
猜你喜欢
  • 2020-03-22
  • 2019-05-25
  • 2021-04-19
  • 1970-01-01
  • 2021-04-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-22
相关资源
最近更新 更多