Express-validator不会“看到”我的表单字段

时间:2018-03-14 11:13:35

标签: node.js express express-validator

当客户端发送带有multipart / form-data编码的表单时,express-validator“check”中间件链不会“看到”表单字段,更不用说验证它们了。是否应该使用一些我不知道的解析中间件或者我错过了什么?没有验证器,下面的强大成功“看到”并提取字段。 我没有任何解决方案,已经多次读过快速验证器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

1 个答案:

答案 0 :(得分:0)

如强大的自述文件中所述,&#34;这是一个低级别的包#34;因此适合与Node的http模块一起使用。

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

现在,您的代码存在问题:

  1. 表示&#39; &#34;标准&#34;正文解析器body-parser,不处理多部分请求。 因此,如果您发送任何其他内容(urlencoded或JSON请求),express-validator将正常工作。
  2. 您在正文解析之前指定了验证。因此,当express-validator执行其操作时,它将看到空req.body 即使强大的开箱即用的快递,根据你的代码,验证任何东西都为时已晚。
  3. 作为附注,在我看来,如果你想要100%快递,更好的选择是multer