如何解决 Express Validator 中间件错误?

huangapple go评论77阅读模式
英文:

How do I Solve Express Validator Middleware Error?

问题

以下是您要翻译的内容:

首先,我有一个像这样的userController:

文件userController.js

const { validationResults } = require('express-validator');
const { userSignUpValidation } = require('../validator/userSignUpValidate');


function userCreation(req, res) {
    try{
        const errors = validationResults(req);
        if(errors) {
            return res.status(400)
            .json({
                error: {
                    message: errors.array()[0].msg
                }
            })
        }

        bcrypt.hash(req.body.userPassword, saltRounds, function(err, hash) {
            User.create({
                userId: req.body.userId,
                userEmail: req.body.userEmail,
                userPhoneNumber: req.body.userPhoneNumber,
                userPassword: hash
            })
            .then((user) => {
                return res.status(200).json(user);
            })
            .catch((error) => {
                return res.status(400).json.error;
            });
        });
    } catch(error) {
        return res.status(400)
        .json({
            error: {
                message: error
            }
        })
    }
}

validator/userSignUpValidate.js中的代码如下:

'use strict';

const { check } = require('express-validator');

module.exports = [
    check('userId').isLength({ min: 5 }).withMessage('用户名至少要有5个字符!'),
    check('userPassword').isLength({ min: 6 }).withMessage('密码至少要有6个字符!'),
    check('userPhoneNumber').isLength({ min: 10 }).withMessage('电话号码至少要有10个字符!'),
    check('userEmail').isEmail().withMessage('您的电子邮件正确吗?请检查并确保正确!')
]

当我在Postman上测试它时,JSON响应总是在userController.js中的catch块中显示错误,但没有错误消息。

{
    "error": {
        "message": {}
    }
}

我的问题是,为了确保express-validator在正确的位置运行,我应该将代码放在哪里?

英文:

First, I have userController like this:

File userController.js

const { validationResults } = require('express-validator');
const { userSignUpValidation } = require('../validator/userSignUpValidate');


function userCreation(req, res) {
    try{
        const errors = validationResults(req);
        if(errors) {
            return res.status(400)
            .json({
                error: {
                    message: errors.array()[0].msg
                }
            })
        }

        bcrypt.hash(req.body.userPassword, saltRounds, function(err, hash) {
            User.create({
                userId: req.body.userId,
                userEmail: req.body.userEmail,
                userPhoneNumber: req.body.userPhoneNumber,
                userPassword: hash
            })
            .then((user) => {
                return res.status(200).json(user);
            })
            .catch((error) => {
                return res.status(400).json.error;
            });
        });
    } catch(error) {
        return res.status(400)
        .json({
            error: {
                message: error
            }
        })
    }
}

In the validator/userSignUpValidate.js the code like this:

'use strict'

const { check } = require('express-validator');

module.exports = [
    check('userId').isLength({ min: 5 }).withMessage('The username at least more than 5 characters!'),
    check('userPassword').isLength({ min: 6 }).withMessage('The password at least more than 6 characters!'),
    check('userPhoneNumber').isLength({ min: 10 }).withMessage('The phone number at least more than 10 characters!'),
    check('userEmail').isEmail().withMessage('Is your email correct? Please be correct!')
]

When I test it on postman, the json response always show error by catch on userController.js without error message.

{
    "error": {
        "message": {}
    }
}

<br>
My question. To ensure the express-validator run in the right place, where should I put the code?

答案1

得分: 2

首先,你需要从express-validator中导入validationResult,在你的代码中你导入了validationResults

其次,你没有使用你的userSignUpValidate中间件。这个中间件可以在控制器中使用,但最好将其应用在userRoute中,以保持控制器的清晰度。

所以让我们将userSignUpValidate中间件应用到userRoutes中。如果文件路径与你的不匹配,请修复它们。

const express = require("express");
const router = express.Router();
const usersController = require("../controllers/userController");
const userSignUpValidate = require("../validator/userSignUpValidate");

router.post("/register", [userSignUpValidate], usersController.userCreation);

module.exports = router;

然后在控制器中,我们需要从express-validator中导入validationResult并使用它:

const { validationResult } = require("express-validator");

function userCreation(req, res) {
  try {
    const errors = validationResult(req);
    if(!errors.isEmpty()) {
      console.log(errors);
      return res.status(400).json({
        error: {
          message: errors.array()[0].msg
        }
      });
    }

    //其他你的代码
  } catch (error) {
    return res.status(400).json({
      error: {
        message: error
      }
    });
  }
}

exports.userCreation = userCreation;

当我们发送一个包含3个字符密码的请求体时,就像这样:

{
  "userId": "userid",
  "userPassword": "123",
  "userPhoneNumber": "1234567890",
  "userEmail": "abc@gmail.com"
}

响应将会是这样,带有400 - 错误请求:

{
    "error": {
        "message": "密码至少需要6个字符以上!"
    }
}
英文:

Firstly you need to import validationResult from express-validator, in your code you are importing validationResults.

Secondly, you are not using your userSignUpValidate middleware. This middleware can be used in controller but it is better to appy it in the userRoute to keep controller clean.

So let's apply userSignUpValidate middleware to the userRoutes.
If the file paths don't match yours, please fix them.

const express = require(&quot;express&quot;);
const router = express.Router();
const usersController = require(&quot;../controllers/userController&quot;);
const userSignUpValidate = require(&quot;../validator/userSignUpValidate&quot;);

router.post(&quot;/register&quot;, [userSignUpValidate], usersController.userCreation);

module.exports = router;

Then in the controller, we need to import validationResult from express-validator and use it:

const { validationResult } = require(&quot;express-validator&quot;);

function userCreation(req, res) {
  try {
    const errors = validationResult(req);
    if(!errors.isEmpty()) {
      console.log(errors);
      return res.status(400).json({
        error: {
          message: errors.array()[0].msg
        }
      });
    }

    //other code you have
  } catch (error) {
    return res.status(400).json({
      error: {
        message: error
      }
    });
  }
}

exports.userCreation = userCreation;

When we send a request body with a 3 character password like this:

{
  &quot;userId&quot;: &quot;userid&quot;,
  &quot;userPassword&quot;: &quot;123&quot;,
  &quot;userPhoneNumber&quot;: &quot;1234567890&quot;,
  &quot;userEmail&quot;: &quot;abc@gmail.com&quot;
}

The response will be like this with a 400 - Bad Request:

{
    &quot;error&quot;: {
        &quot;message&quot;: &quot;The password at least more than 6 characters!&quot;
    }
}

答案2

得分: 0

你应该像这样传递:

const errors = validationResults(req.body);

英文:

you should pass like this

const errors = validationResults(req.body);

答案3

得分: 0

以下是您的代码的中文翻译:

const Joi = require('@hapi/joi');
const loginValidation = data => {
    const schema = {
        username: Joi.string().min(5).required(),
        password: Joi.string().min(5).required(),
        deviceId: Joi.string().min(2).required()
    };
    return Joi.validate(data, schema);
};
module.exports.loginValidation = loginValidation;

// 我的路由文件

const { registerValidation, loginValidation } = require('../../validation');
router.post('/login', async (req, res) => {
    try {
        // 验证要提交的数据
        const { error } = loginValidation(req.body);
        if (error) return res.status(200).send(
            {
                status: 0,
                message: "验证错误",
                details: error.details[0].message
            });
             
    } catch (error) {
        res.status(400).send({
            status: 0,
            message: "失败",
            error: error
        });
    }
});

这段代码正常运行且处于生产模式。

英文:
 const Joi = require(&#39;@hapi/joi&#39;);                                           
 const loginValidation = data =&gt;{    const schema = {
    username: Joi.string().min(5).required(),
    password: Joi.string().min(5).required(),
    deviceId: Joi.string().min(2).required()
};
return Joi.validate(data, schema); };                   
module.exports.loginValidation = loginValidation;                                 

> My Routes File

const { registerValidation, loginValidation } = require(&#39;../../validation&#39;);   router.post(&#39;/login&#39;, async (req, res)=&gt;{
try {
    //validate the data to be submitted
    const { error } = loginValidation(req.body);
    if (error) return res.status(200).send(
        {
            status: 0,
            message: &quot;Validarion Error&quot;,
            details: error.details[0].message
        });
         
} catch (error) {
    res.status(400).send({
        status: 0,
        message: &quot;Failed&quot;,
        error: error
    });
}});

this code works fine and is in production mode

答案4

得分: 0

Here's the translated code snippet:

只需尝试如下

const express = require('express');
const { check, oneOf, validationResult } = require('express-validator');

const app = express();

// 这个函数需要在控制器中导出
const xxx = (req, res, next) => {
  try {
    validationResult(req).throw();
    res.status(200).send('success');
  } catch (err) {
    console.log('error message came');
    res.status(422).json(err);
  }
}

app.get('/', oneOf([
  check('lang').isIn(['js', 'react', 'angular'])
]), xxx);

app.listen(4000, () => {
  console.log("running server 4k")
})

Please note that the code appears to be in JavaScript and uses the Express.js framework with some validation logic.

英文:

Just try like below,

const express = require(&#39;express&#39;);
const { check, oneOf, validationResult } = require(&#39;express-validator&#39;);


const app = express();

//this function you need to export in controller
const xxx = (req, res, next) =&gt; {
  try {
    validationResult(req).throw();
    res.status(200).send(&#39;success&#39;);
  } catch (err) {
    console.log(&#39;error messagecame&#39;)
    res.status(422).json(err);
  }
}

app.get(&#39;/&#39;, oneOf([
  check(&#39;lang&#39;).isIn([&#39;js&#39;, &#39;react&#39;, &#39;angular&#39;])
]), xxx);

app.listen(4000, ()=&gt;{
  console.log(&quot;running server 4k&quot;)
})

Sample working copy

UPDATE 2

I hope below one will help full,

const express = require(&#39;express&#39;);
const { check, oneOf, validationResult } = require(&#39;express-validator&#39;);

const app = express();
const xxx = [
  check(&#39;lang&#39;).isIn([&#39;js&#39;, &#39;react&#39;, &#39;angular&#39;]),
  (req, res, next) =&gt; {
    try {
      validationResult(req).throw();
      res.status(200).send(&#39;success&#39;);
    } catch (err) {
      console.log(&#39;error messagecame&#39;)
      res.status(422).json(err);
    }
  }
]

app.get(&#39;/&#39;, xxx);

app.listen(4000, ()=&gt;{
  console.log(&quot;running server 4k&quot;)
})

SAMPLE WORKING COPY2

Error

https://TruthfulWeirdIrc--five-nine.repl.co?lang=jssddf

Success

https://TruthfulWeirdIrc--five-nine.repl.co?lang=js

huangapple
  • 本文由 发表于 2020年1月6日 15:21:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/59608129.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定