1

当客户端发送带有 multipart/form-data 编码的表单时,express-validator“检查”中间件链不会“看到”表单字段,更不用说验证它们了。它应该与一些我不知道的解析中间件一起工作还是我错过了什么?如果没有验证器,强大的下面会成功“看到”并提取字段。我已经多次阅读 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
4

1 回答 1

0

正如在强大的 README 中提到的,“这是一个低级包”。因此适合与 Node 的http模块一起使用。

您不能简单地将其作为 express 中间件传递,并且正文解析是按照自己的方式完成的。

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

  1. express'“标准”正文解析器,body-parser不处理多部分请求。因此,如果您发送任何其他内容(urlencoded 或 JSON 请求),express-validator 将正常工作。
  2. 您在正文解析发生之前指定了验证。所以当 express-validator 做它的事情时,它会看到一个空的req.body.
    即使强大的使用 express 开箱即用,根据您的代码,验证任何内容都为时已晚。

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

于 2018-03-16T00:19:48.833 回答