首页 > 解决方案 > 请求正文长度中的字符串在 Express&&bodyparser 中始终受到限制

问题描述

我在 express4&body 解析器中遇到了一个非常烦人的问题。

在前端,我得到一个表单,其输入包含一个很长的字符串,例如 5,000,000 长,接近 5MB。

提交此表单后,我会在快速路由中打印此输入:console.log(req.body.inputname.length),奇怪的是长度始终限制为 1,048,553,非常接近 1MB。没有错误/异常发生。

我已经将 bodyparser 限制大小设置为 50MB,并使用 input(type =file) 对其进行了测试,当我上传大尺寸文件时它正在工作,所以我猜大小​​限制不是问题。

基本上我在前端将图像上传到输入(类型=文件),然后在前端我使用 fileReader 将其转换为 base64 字符串并通过发布请求提交该字符串。这就是为什么我能得到这么长的字符串。

前端(我用过jade和Vue)

form(method='post',action="/upload",enctype='multipart/form-data')
  input(type='file', @change='previewImages($event)', multiple='multiple')
  input.hidden-input(type='hidden' name='imagesArray' v-model='imagesArray')

script.
  //In vue instance,
  data:{
  imagesArray:[];
   }
  methods{
    previewImages(event){
       function readAndPreview(){
          let reader = new FileReader();
          reader.addEventListener("load", function (e) {
             ourVueInstance.imagesArray.push(e.target.result);},false);
          reader.readAsDataURL(file);
     }  
     [].forEach.call(event.target.files, readAndPreview);
    }
 }

路由器(使用快递应用)

app.post('/upload',(req,res)=>{
//imageArray is converted to string, and its length is now limited to 1048553
console.log(req.body.imagesArray.length)
})

bodyparser 设置

app.use(bodyParser.json({ limit: '50mb',length:'1000000000' })); 
app.use(bodyParser.urlencoded({limit:'50mb',extended: true,parameterLimit:50000,length:'1000000000'})); 

添加: server.js

var cluster = require('cluster');
var sticky  = require('sticky-cluster');
var util    = require('./util/util.js');
var fs = require('fs');
var ejs = require('ejs');
var session = require('express-session');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var i18n = require('i18n-express');
var mongoose = require('mongoose');
var MongoStore = require('connect-mongo')(session);
var morgan =  require('morgan');
var flash = require('connect-flash');
var config = require('./config/config.json');
var log = require('./util/log.js').getLogger(__filename);
var passport = require('passport');
var validator =  require('express-validator');
var port = config.our_SERVER_PORT;
var sslport = config.our_SERVER_SSL_PORT;

const fileUpload = require('express-fileupload');

//var LocalStrategy = require('passport-local').Strategy;
require('./config/passport');

// running applications on the master process
var express = require('express');
var app = express();

app.use(fileUpload());
app.use(morgan('dev'));  // log every request to the console
app.use(express.static(__dirname + '/public'));
app.use(express.static(config.IMAGE_BASE_PATH));

//initialize the DB connections
//load configuration details from the server configuration JSON
var dbURL = config.DB_URL;
log.info("Initializing the DB connection. " + dbURL);
mongoose.Promise = global.Promise;
mongoose.connect(dbURL, {useMongoClient:true});

app.use(cookieParser(config.SESSION.SESSION_SECRET)); // read cookies (needed for auth)

app.use(session({
    secret: config.SESSION.SESSION_SECRET,
    resave: true,
    saveUninitialized: true,
    store: new MongoStore({url: dbURL}),
    cookie: {maxAge: config.SESSION.COOKIE_MAXAGE_MS}
}));

app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(validator());

//sign in protection
app.use(function (req, res, next) {
    res.locals.login = req.isAuthenticated();
    res.locals.session = req.session;

    //To avoid undefined total quantity in topnavbarMain's cart
    if(!req.session.cart){
        req.session.cart={};
    }
    next();
});

//init i18n after cookie-parser
app.use(i18n({
    translationsPath: __dirname +  '/i18n',
    siteLangs: config.SUPPORTED_LANGUAGE,
    cookiename:'ulang'
}));

app.use(bodyParser.json({ limit: '50mb',length:'1000000000' })); // get information from html forms
app.use(bodyParser.urlencoded({limit:'50mb',extended: true,parameterLimit:50000,length:'1000000000'}));


app.set('views', __dirname + '/views');

app.set('view engine', "pug");
app.engine('pug', require('pug').__express);

app.use(flash());  // use connect-flash for flash message stored in session

//CA certificate for HTTPS
var options = {};
var http, https;

// sticky options
var stickySSLOptions = {
    concurrency: require('os').cpus().length,
    //concurrency:1,
    port: config.our_SERVER_SSL_PORT,
    debug: true
};

// sticky options
var stickyOptions = {
    concurrency: require('os').cpus().length,
    //concurrency:1,
    port: config.our_SERVER_PORT,
    debug: true
};

// configuration enables the CA cert with SSL enabled
if (config.CA_CERT.SSL_ENABLED) {

    sticky(
        // server initialization function
        function(callback) {
            options = {
                ca   : fs.readFileSync(__dirname + '/cert/' + config.CA_CERT.SSL_CA),
                key  : fs.readFileSync(__dirname + '/cert/' + config.CA_CERT.SSL_KEY),
                cert : fs.readFileSync(__dirname + '/cert/' + config.CA_CERT.SSL_CERT),
                passphrase: config.CA_CERT.passphrase
            };

            https = require('https').createServer(options, app);

            callback(https);
        },

        stickySSLOptions
    );

}
else {
    // non SSL
    sticky(
        function(callback) {
            http = require('http').createServer(app);

            callback(http);
        },

        stickyOptions
    );
}

//routes
//require routes goes here. I will not list them for space. 


/******************************************************
 * error handlers
 ******************************************************/
// catch 404 and forward to error handler
app.use(function(req, res, next) {
    let err = new Error('.............');
    err.status = 404;
    next(err);
});

// error handler
app.use(function(err, req, res, next) {
    // set locals, only providing error in development
    res.locals.errMsg = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};

    // render the error page
    res.status(err.status || 500);
    res.render('common/error');
});


//check if we are running master process
if (cluster.isMaster) {
    // Listen for dying workers
    cluster.on('exit', function (worker) {
        // Replace the dead worker
        console.log('Worker %d died :(', worker.id);
        log.info("Worker " +  worker.id + " died. Replace with a new worker to serve for the application.");
        cluster.fork();
    });
}

对此有什么想法吗?任何解决方案/尝试将不胜感激,非常感谢!

标签: node.jsexpresshttprequeststring-lengthbody-parser

解决方案


推荐阅读