Express-validator 没有 "see" 我的表单字段

Express-validator does not "see" my form fields

当客户端发送带有 multipart/form-data 编码的表单时,express-validator "check" 中间件链不会 "see" 表单字段,更不用说验证它们了。它应该与一些我不知道的解析中间件一起使用还是我错过了什么?在没有验证器的情况下,强大的下面成功地 "sees" 并提取了字段。 我已经阅读了 express-validator README 很多遍了,没有任何解决方案。

const express = require('express');
const router = express.Router();
const formidable = require('formidable');
const bcrypt = require('bcryptjs');
const mysql = require('mysql');
const uuid = require('uuid/v4');
const { check, validationResult } = require('express-validator/check');

router.post('/files', function () {
//Handle profile picture uploads here. End request;
});

//Sanitize, validate. Ends req if err
// noinspection JSUnresolvedFunction
router.post("/",[
check('alias')
    .exists() 
    .withMessage("ER_NO_ALIAS_FIELD") //Message is returned in result yet formidable
    .not()                            //below is able to extract the fields
    .isEmpty()                        //Proves that express-validator doesn't "see"
    .withMessage("ER_NO_NAME")        //the fields.
    .isFullWidth()
    .withMessage('ER_NAME_HALF_WIDTH')
    .escape()
    .trim(),
check('email')
    .exists()
    .withMessage("ER_NO_EMAIL_FIELD") //Message is returned
    .not()
    .isEmpty()
    .withMessage('ER_NO_EMAIL')
    .isEmail()
    .withMessage('ER_EMAIL_FORMAT')
    .trim()
    .normalizeEmail(),
check('sex')
    .isIn(['M', 'F'])
    .withMessage('ER_SEX'),
check('dob')
    .not()
    .isEmpty()
    .withMessage('ER_NO_DOB'),
check('pref')
    .not()
    .isEmpty()
    .withMessage('ER_NO_PREF'),
check('about')
    .not()
    .isEmpty()
    .withMessage("ER_NO_ABOUT") //To prevent the subsequent errors from being sent. Works because of "onlyFirstError: true"
    .isLength({max: 255})
    .withMessage('ER_ABOUT_LENGTH')
    .isFullWidth()
    .withMessage('ER_ABOUT_HALF_WIDTH')
    .trim()
    .escape(),
check('school')
    .not()
    .isEmpty()
    .withMessage("ER_NO_SCHOOL") //To prevent the subsequent errors from being sent. Works because of "onlyFirstError: true"
    .isFullWidth()
    .withMessage("ER_SCH_HALF_WIDTH")
    .isLength({max: 255})
    .withMessage("ER_SCH_LENGTH")
    .trim()
    .escape(),
check('password')
    .not()
    .isEmpty()
    .withMessage("ER_NO_PASSWD")
], (req, res)=>{
//Check the validation result here
let result = validationResult(req);
if(result.isEmpty()) {
    next();
} else {
    //Format the errors and echo them back to the client
    //The query ends here
    res.writeHead(200, {'Content-Type':'text/html', 'Access-Control-Allow-Origin': 'http://localhost:3000'});
    res.write("<?xml version='1.0' encoding='UTF-8' ?>");
    res.write(`<cookie>${res.getHeader('Set-Cookie')}</cookie>`); //DEV

    //Return an array of validation results/errors. Only the first error
    let error_array = result.array({onlyFirstError: true});

    res.write(`<err_arr>${JSON.stringify(error_array)}</err_arr>`);
    res.write("<msg>There was a problem with the form entries</msg>");

    res.end("<srv_res_status>8</srv_res_status>");
}
});

router.post('/', function (req, res) {
res.writeHead(200, {'Content-Type':'text/html', 'Access-Control-Allow-Origin': 'http://localhost:3000'});
res.write("<?xml version='1.0' encoding='UTF-8' ?>");
let form = new formidable.IncomingForm();
form.parse(req, (err, fields, files)=>{
    if(err) throw err;
    //fields contains the form fields

如 formidable 的 README 中所述,"This is a low-level package"。因此适合与 Node 的 http 模块一起使用。

你不能简单地将它作为一个 express 中间件传递,主体解析是按照自己的方式完成的。

现在,关于您的代码的问题:

  1. express' "standard" 正文解析器 body-parser 不处理多部分请求。 因此,如果您发送任何其他内容(urlencoded 或 JSON 请求),express-validator 将正常工作。
  2. 您在正文解析发生之前指定了您的验证。所以当 express-validator 执行它的操作时,它会看到一个空的 req.body.
    即使 formidable 使用 express out-of-box,根据您的代码,验证任何内容都为时已晚。

附带说明一下,在我看来,如果您想使用 100% 快递,更好的选择是 multer