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

时间:2021-09-25 19:57:41

I need a simple way to access multipart form data in the req object using busboy-connect. I'm using Express 4, which now needs modules for previously built-in functionality.

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

I want the req.body object to be available in my routes, but the busboy.on('field') function is async and doesn't process all form data before passing it off to continue down the code.

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

There is a middleware module built on top of busboy called multer, which gets the req.body object before getting to the route, however it overrides the ability to define the busboy.on('file') event from within the route.

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

Here's my broken code:

这是我破碎的代码:

// 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.
 });

UPDATE I'm using connect-busboy. I used this middleware code in my express setup file to give me access to the req.body object within my route. I can also process the file upload from within my route and have access to the req.busbuy.on('end').

更新我正在使用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();
   });
 });

1 个解决方案

#1


9  

Try adding:

busboy.on('finish', function() {
  // use req.body
});

#1


9  

Try adding:

busboy.on('finish', function() {
  // use req.body
});