因此,我正在使用基本的node.js + express制作此登录身份验证应用。因此,当我从注册页面获取值(名称,电子邮件等)时,我正在使用express-validator验证值。但是,当注册页面表单具有enctype ='multipart / form-data'时,我得到的每个值都未定义(名称,电子邮件等)。但是当我删除enctype ='multipart / form-data'时,值就很好了!!

那么对此有什么解决方案吗?我只是Node.js的初学者。

(PS。我需要enctype ='multipart / form-data',因为我是在注册时上传个人资料图片的)

(PS在代码中,我删除了中间件,以显示仅用于register.jade及其路由的最少代码)

我没有使用enctype ='multipart / form-data'成功注册,但是在这里我无法上传图像。

(PS使用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.jade

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',并且其余值不会被设置为undefined,因为那样我的express-validator无法正常工作

最佳答案

使用'multipart/form-data'会阻止Express分析其他表单字段的值。解决此问题的最简单方法是使用中间件,该中间件解析多部分表单,并允许您同时访问字段和图像。

有几种这样的中间件软件包,每个都有自己的支持/文档​​/跟踪记录:multerbusboymultiparty等。过去,我在多个项目中使用了多方协作,没有问题,但是有较新的软件包。

关于javascript - 当表单设置为enctype ='multipart/form-data'时,express-validator提供未定义的值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56743216/

10-11 05:31