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

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('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!')
]

当我在 postman 上测试它时,json 响应总是在 userController.js 上显示 catch 错误,没有错误消息。

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


我的问题。为了确保express-validator 运行在正确的地方,我应该把代码放在哪里?

你应该这样通过

const errors = validationResults(req.body);

 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;                                 

My Routes File

const { registerValidation, loginValidation } = require('../../validation');   router.post('/login', async (req, res)=>{
try {
    //validate the data to be submitted
    const { error } = loginValidation(req.body);
    if (error) return res.status(200).send(
        {
            status: 0,
            message: "Validarion Error",
            details: error.details[0].message
        });

} catch (error) {
    res.status(400).send({
        status: 0,
        message: "Failed",
        error: error
    });
}});

这段代码工作正常并且处于生产模式

试试下面的方法,

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


const app = express();

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

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

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

Sample working copy

更新 2

希望下面一位对你有所帮助,

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

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

app.get('/', xxx);

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

SAMPLE WORKING COPY2

错误

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

成功

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

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

其次,您没有使用 userSignUpValidate 中间件。这个中间件可以在controller中使用,但是最好将它应用在userRoute中以保持controller干净。

所以让我们将 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
        }
      });
    }

    //other code you have
  } 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": "The password at least more than 6 characters!"
    }
}