【发布时间】:2014-06-30 11:33:55
【问题描述】:
我需要一种简单的方法来使用 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.
});
更新 我正在使用连接总线男孩。我在我的快速设置文件中使用了这个中间件代码,让我可以访问我的路由中的 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();
});
});
【问题讨论】:
-
我有同样的问题你介意解释一下这段代码是如何工作的吗?我的所有请求都在单独的路由中处理,这个解决方案不适用于我的代码。也许如果我对您的工作有更好的了解,这将帮助我解决我的问题!这是我的第一个节点项目。
-
@JeffPowers 我无法让中间件像我想象的那样工作。目前没有解决方案来解析“不同”位置的传入 Multipart 数据,例如只解析字段,然后对字段数据做一些事情,然后再解析文件,然后调用 busboy.on(“finish”)。请在此处查看我的帖子:programmers.stackexchange.com/questions/239170/… 如果您有任何发现,请告诉我。我最终在我的控制器中放置了大量的逻辑......这不是一个好的设计选择,但我放弃了。
-
我得出了同样的结论,我实际上把 busboy 换成了 multer:github.com/expressjs/multer。这要简单得多。
标签: node.js express routes multipartform-data