当表单设置为 enctype='multipart/form-data' 时,express-validator 给出未定义的值
express-validator giving undefined value when form set to enctype='multipart/form-data'
所以我正在使用基本 node.js+express 制作这个登录授权应用程序。因此,当我从注册页面获取值(姓名、电子邮件等)时,我正在使用 express-validator 验证这些值。但是,当注册页面表单具有 enctype='multipart/form-data' 时,我得到的每个值都未定义(名称、电子邮件等)。但是当我删除 enctype='multipart/form-data' 时,这些值就很好了!!
有什么解决办法吗?我只是 Node.js.
的初学者
(P.S。我需要 enctype='multipart/form-data' 因为我在注册时上传了个人资料图片)
(P.S 在代码中我删除了中间件以显示仅 register.jade 及其路由的最少代码)
我在没有使用enctype='multipart/form-data'的情况下注册成功,但是这里无法上传图片
(P.S。使用 multer 上传文件)
./app.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var logger = require('morgan');
var expressValidator = require('express-validator');
var session = require("express-session");
var passport = require("passport");
var localStratergy = require("passport-local").Strategy;
var multer = require("multer");
var upload = multer({dest: './uploads'});
var flash = require("connect-flash");
var bcrypt = require("bcryptjs");
var moongo = require("mongodb");
var mongoose = require("mongoose");
var db = mongoose.connection;
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
const { check, validationResult } = require('express-validator');
var app = express();
app.use('/', indexRouter);
app.use('/users', usersRouter);
module.exports = app;
./routes/user.js
var express = require('express');
var router = express.Router();
var multer = require("multer");
var bodyParser = require('body-parser');
var passport = require("passport");
var LocalStrategy = require("passport-local").Strategy;
var User = require('../models/user');
router.use(bodyParser.json());
router.use(bodyParser.urlencoded({ extended: false }));
var upload = multer({dest: './uploads'});
const {check, validationResult} = require('express-validator');
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
router.get('/register', function(req, res, next) {
res.render('register', {title: 'Register'});
});
router.post('/register', [
check('name' , 'Name Field is required').not().isEmpty(),
check('email', 'Email Field is required').not().isEmpty(),
check('email', 'Email Field is not valid').isEmail(),
check('username', 'Username Field is required').not().isEmpty(),
check('password', 'Password Field is required').not().isEmpty(),
check('password2', 'Passwords do not match').custom(
(value, {req, loc, path}) => {
if( value != req.body.password) {
throw new error("Passwords do not match");
} else{
return value;
}
})
], upload.single('profileimage'),function(req, res, next) {
var name = req.body.name;
var email = req.body.email;
var username = req.body.username;
var password = req.body.password;
var password2 = req.body.password2;
if(req.file){
console.log("Uploading");
var profileimage = req.file.filename;
} else{
console.log("No File Selected");
var profileimage = "noimage.jpg";
}
const errors = validationResult(req);
if(!errors.isEmpty()){
res.render('register', {
error: errors.array()
})
} else{
var newUser = new User({
name: name,
email: email,
username: username,
password: password,
profileimage: profileimage
});
User.createUser(newUser, function(err, user){
if(err) throw err;
console.log(user);
});
req.flash('success', 'You have now registered');
res.location('/');
res.redirect('/');
}
});
module.exports = router;
./views/register.玉
extends layout
block content
h2.page-header Register
p Please Register Below
if error
each errors, i in error
div.alert.alert-danger #{errors.msg}
form(action="/users/register", method="post" enctype='multipart/form-data')
.form-group
label Name
input.form-control(name="name", type="text", placeholder="Enter Name", class="name")
.form-group
label Email
input.form-control(name="email", type="email", placeholder="Enter Email")
.form-group
label Username
input.form-control(name="username", type="text", placeholder="Enter Username")
.form-group
label Password
input.form-control(name="password", type="password", placeholder="Enter password")
.form-group
label Retype Password
input.form-control(name="password2", type="password", placeholder="Enter password again")
.form-group
label Profile Image
input.form-control(name="profileimage", type="File")
input.btn.btn-primary(type="submit", name="submit", value="Register")
我希望我的图片上传包含 enctype='multipart/form-data' 并且其余值不会设置为未定义,因为这样我的快速验证器就无法正常工作
您使用 'multipart/form-data'
会阻止 Express 解析其他表单字段的值。解决这个问题的最简单方法是使用解析多部分表单的中间件,并让您访问两个字段和 image/s.
有几个这样的中间件包,每个都有自己的support/documentation/track记录:multer, busboy, multiparty等。我过去在几个项目中使用过multiparty,没有问题,但是有更新的包。
我解决了修改中间件顺序(在 Router 中)的问题:首先必须去 Multer,然后 Express-Validator。
(我认为这是因为 Multer 在 req.body 中添加了字段,所以:首先您必须添加这些字段,然后进行验证。
这样就可以了,因为multer在前:
router.post('/register',multerUploadUser.single('user_photo'), verificationRegister, userController.registerUpload);
这样,不:
router.post('/register', verificationRegister, multerUploadUser.single('user_photo'), userController.registerUpload);
所以我正在使用基本 node.js+express 制作这个登录授权应用程序。因此,当我从注册页面获取值(姓名、电子邮件等)时,我正在使用 express-validator 验证这些值。但是,当注册页面表单具有 enctype='multipart/form-data' 时,我得到的每个值都未定义(名称、电子邮件等)。但是当我删除 enctype='multipart/form-data' 时,这些值就很好了!!
有什么解决办法吗?我只是 Node.js.
的初学者(P.S。我需要 enctype='multipart/form-data' 因为我在注册时上传了个人资料图片)
(P.S 在代码中我删除了中间件以显示仅 register.jade 及其路由的最少代码)
我在没有使用enctype='multipart/form-data'的情况下注册成功,但是这里无法上传图片
(P.S。使用 multer 上传文件)
./app.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var logger = require('morgan');
var expressValidator = require('express-validator');
var session = require("express-session");
var passport = require("passport");
var localStratergy = require("passport-local").Strategy;
var multer = require("multer");
var upload = multer({dest: './uploads'});
var flash = require("connect-flash");
var bcrypt = require("bcryptjs");
var moongo = require("mongodb");
var mongoose = require("mongoose");
var db = mongoose.connection;
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
const { check, validationResult } = require('express-validator');
var app = express();
app.use('/', indexRouter);
app.use('/users', usersRouter);
module.exports = app;
./routes/user.js
var express = require('express');
var router = express.Router();
var multer = require("multer");
var bodyParser = require('body-parser');
var passport = require("passport");
var LocalStrategy = require("passport-local").Strategy;
var User = require('../models/user');
router.use(bodyParser.json());
router.use(bodyParser.urlencoded({ extended: false }));
var upload = multer({dest: './uploads'});
const {check, validationResult} = require('express-validator');
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
router.get('/register', function(req, res, next) {
res.render('register', {title: 'Register'});
});
router.post('/register', [
check('name' , 'Name Field is required').not().isEmpty(),
check('email', 'Email Field is required').not().isEmpty(),
check('email', 'Email Field is not valid').isEmail(),
check('username', 'Username Field is required').not().isEmpty(),
check('password', 'Password Field is required').not().isEmpty(),
check('password2', 'Passwords do not match').custom(
(value, {req, loc, path}) => {
if( value != req.body.password) {
throw new error("Passwords do not match");
} else{
return value;
}
})
], upload.single('profileimage'),function(req, res, next) {
var name = req.body.name;
var email = req.body.email;
var username = req.body.username;
var password = req.body.password;
var password2 = req.body.password2;
if(req.file){
console.log("Uploading");
var profileimage = req.file.filename;
} else{
console.log("No File Selected");
var profileimage = "noimage.jpg";
}
const errors = validationResult(req);
if(!errors.isEmpty()){
res.render('register', {
error: errors.array()
})
} else{
var newUser = new User({
name: name,
email: email,
username: username,
password: password,
profileimage: profileimage
});
User.createUser(newUser, function(err, user){
if(err) throw err;
console.log(user);
});
req.flash('success', 'You have now registered');
res.location('/');
res.redirect('/');
}
});
module.exports = router;
./views/register.玉
extends layout
block content
h2.page-header Register
p Please Register Below
if error
each errors, i in error
div.alert.alert-danger #{errors.msg}
form(action="/users/register", method="post" enctype='multipart/form-data')
.form-group
label Name
input.form-control(name="name", type="text", placeholder="Enter Name", class="name")
.form-group
label Email
input.form-control(name="email", type="email", placeholder="Enter Email")
.form-group
label Username
input.form-control(name="username", type="text", placeholder="Enter Username")
.form-group
label Password
input.form-control(name="password", type="password", placeholder="Enter password")
.form-group
label Retype Password
input.form-control(name="password2", type="password", placeholder="Enter password again")
.form-group
label Profile Image
input.form-control(name="profileimage", type="File")
input.btn.btn-primary(type="submit", name="submit", value="Register")
我希望我的图片上传包含 enctype='multipart/form-data' 并且其余值不会设置为未定义,因为这样我的快速验证器就无法正常工作
您使用 'multipart/form-data'
会阻止 Express 解析其他表单字段的值。解决这个问题的最简单方法是使用解析多部分表单的中间件,并让您访问两个字段和 image/s.
有几个这样的中间件包,每个都有自己的support/documentation/track记录:multer, busboy, multiparty等。我过去在几个项目中使用过multiparty,没有问题,但是有更新的包。
我解决了修改中间件顺序(在 Router 中)的问题:首先必须去 Multer,然后 Express-Validator。 (我认为这是因为 Multer 在 req.body 中添加了字段,所以:首先您必须添加这些字段,然后进行验证。
这样就可以了,因为multer在前:
router.post('/register',multerUploadUser.single('user_photo'), verificationRegister, userController.registerUpload);
这样,不:
router.post('/register', verificationRegister, multerUploadUser.single('user_photo'), userController.registerUpload);