我有一个 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?