如何使用Busboy访问Express 4 req.body对象

Sco*_*ott 7 routes multipartform-data node.js express

我需要一种简单的方法来使用busboy-connect访问req对象中的多部分表单数据.我正在使用Express 4,它现在需要以前内置功能的模块.

我希望req.body对象在我的路由中可用,但是busboy.on('field')函数是异步的,并且在传递它以继续关闭代码之前不会处理所有表单数据.

busboy之上构建了一个中间件模块,称为multer,它在到达路径之前获取req.body对象,但是它会覆盖从路径中定义busboy.on('file')事件的能力.

这是我破碎的代码:

// App.js

app.post(/users, function(req, res, next){

  var busboy = new Busboy({ headers: req.headers });

  // handle text field data (code taken from multer.js)
  busboy.on('field', function(fieldname, val, valTruncated, keyTruncated) {
    if (req.body.hasOwnProperty(fieldname)) {
      if (Array.isArray(req.body[fieldname])) {
        req.body[fieldname].push(val);
      } else {
        req.body[fieldname] = [req.body[fieldname], val];
      }
    } else {
      req.body[fieldname] = val;
      console.log(req.body);
    }
  });

  busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {

    tmpUploadPath = path.join(__dirname, "uploads/", filename);
    targetPath = path.join(__dirname, "userpics/", filename);

    self.imageName = filename;
    self.imageUrl = filename;

    file.pipe(fs.createWriteStream(tmpUploadPath));
  });

  req.pipe(busboy); // start piping the data.

  console.log(req.body) // outputs nothing, evaluated before busboy.on('field') 
                        // has completed.
 });
Run Code Online (Sandbox Code Playgroud)

更新 我正在使用connect-busboy.我在快速安装文件中使用了这个中间件代码,以便我可以访问路由中的req.body对象.我还可以从我的路线中处理文件上传,并可以访问req.busbuy.on('end').

 // busboy middleware to grab req. post data for multipart submissions.
 app.use(busboy({ immediate: true }));
 app.use(function(req, res, next) {
   req.busboy.on('field', function(fieldname, val) {
     // console.log(fieldname, val);
     req.body[fieldname] = val;
   });

   req.busboy.on('finish', function(){
     next();
   });
 });
Run Code Online (Sandbox Code Playgroud)

msc*_*dex 9

尝试添加:

busboy.on('finish', function() {
  // use req.body
});
Run Code Online (Sandbox Code Playgroud)

  • 您可以将解决方案缩短为“req.busboy.on('finish', next);” (2认同)