1

我有一个 NodeJS/Express Web 应用程序,它允许用户上传一个文件,然后我使用connect- busboy 解析该文件,并使用Sequelize保存到我的数据库中。完成后,我想将用户重定向到给定页面。但是 Express 在我的 Promise 解决之前返回状态 404,即使我从未调用next(),我认为这是强制性的,以便调用中间件链中的下一个处理程序,从而导致 404。

到目前为止,这是我的代码:

function uploadFormFile(req, res, next) {
   var documentInstanceID = req.params.documentInstanceID;
   // set up an object to hold my data
   var data = {
    file: null,
    documentDate: null,
    mimeType: null
   };
   // call the busboy middleware explicitly 
   // EDIT: this turned out to be the problem... of course this calls next()
   // removing this line and moving it to an app.use() made everything work as expected
   busboy(req, res, next);
   req.pipe(req.busboy);
   req.busboy.on('file', function (fieldName, file, fileName, encoding, mimeType) {
    var fileData = [];
    data.mimeType = mimeType;
    file.on('data', function (chunk) {
        fileData.push(chunk);
    });
    file.on('end', function () {
        data.file = Buffer.concat(fileData);
    });
   });
   req.busboy.on('finish', function () {
    // api methods return promises from Sequelize
    api.querySingle('DocumentInstance', ['Definition'], null, { DocumentInstanceID: documentInstanceID })
        .then(function (documentInstance) {
        documentInstance.RawFileData = data.file;
        documentInstance.FileMimeType = data.mimeType;
        // chaining promise
        return api.save(documentInstance);
       }).then(function () {
        res.redirect('/app/page');
       });
   });
}

我可以确认我的数据被正确保存。但是由于竞争条件,由于 Express 返回 404 状态,网页显示“无法 POST”,并且res.redirect由于在发送 404 后尝试重定向,因此设置标题时出错并失败。

谁能帮我弄清楚为什么 Express 会返回 404?

4

1 回答 1

1

问题来自您对处理程序内部的 busboy 的内部调用。它不是执行并将控制权简单地返回给您的处理程序,而是next在返回控制权之前调用传递给它的 which。所以你在 busboy 调用确实执行之后编码,但请求已经超过了那个点。

如果您希望某些中间件仅针对某些请求执行,您可以将中间件链接到这些请求中,例如:

router.post('/upload',busboy,uploadFromFile)

您还可以将它们分开,.use()例如:

router.use('/upload', busboy);
router.post('/upload', uploadFromFile);

以上任何一种方式都将以您想要的方式链接中间件。在中间件的情况下,.use()也适用.METHOD()于 Express 在其文档中引用的任何适用对象。

另外,请注意,您可以通过这种方式传入任意数量的中间件,既可以作为单独的参数,也可以作为中间件函数的数组,例如:

router.post('/example', preflightCheck, logSomeStuff, theMainHandler);
// or
router.post('example', [ preflightCheck,logSomeStuff ], theMainHandler);

上述任何一个示例的执行行为都是等效的。仅代表我自己,并不建议这是最佳实践,如果我在运行时构建中间件列表,我通常只使用基于数组的中间件添加。

祝你好运。我希望你和我一样喜欢使用 Express。

于 2015-10-09T02:27:02.493 回答