Node.js Express – 在完成处理整个请求之前提供HTTP响应

我有一个Node.js高速服务器,我发送响应,然后尝试使用相同的请求实例做更多的处理。

如果我在发送头文件之后写入res,我将会得到一个错误 – 但是如果我在发回相应的响应的响应之后使用req可读stream,会发生什么?

换句话说,在完成处理整个请求之前,如何使用Node.server发送HTTP响应?

换句话说,如果我已经发回了一个响应,那么在已经发送响应之后,我怎么能“消费”这个请求 – 除了回复响应之外,这其实只是一个事情吗?

现在,似乎有一些奇怪的错误相关的使用请求对象(stream)对应于已经发送的响应。

让我举一些例子,

以下显示了我的服务器中的最后3个Express中间件处理程序。 作为一个有趣的旁注 – 一旦一个中间件处理程序被请求调用,它不能被调用(看起来如此)。 那么会发生什么呢是当响应被发送时,下面的第一个处理程序被调用。 然后,另一个执行path(使用process.nextTick或setImmediate)调用next(),然后调用第二个处理程序,这意味着我最终得到了一个404在我的服务器上login。

app.use(function (req, res, next) { var r; var timeRequired = (Date.now() - req.request_start) + 'ms'; console.log("Time required for request:", timeRequired); if (r = req.lectalTemp) { if (!req.lectalSent) { req.lectalSent = true; res.status(r.status).json({timeRequired: timeRequired, success: r.data}); } else { console.log('Headers sent already, but here is the data that would have been sent:', r); } } else { next(); } }); // catch 404 and forward to error handler app.use(function (req, res, next) { var err = new Error('404: Not Found - ' + req.method + ' ' + req.originalUrl); err.status = 404; next(err); }); app.use(function (err, req, res, next) { var timeRequired = (Date.now() - req.request_start) + 'ms'; if (app.get('env') === 'production') { res.status(err.status || 500).json({ error: 'sorry the API experienced an error serving your priority request' }); } else { console.error(colors.bgRed(err), '\n', err.stack); if (!res.headersSent && !req.lectalSent) { req.lectalSent = true; res.status(err.status || 500).json({ error: { timeRequired: timeRequired, errMessage: err.message, errStack: err.stack } }); } } }); 

我会用队列解决这个问题。 将低关键数据的消息发布到队列中(例如RabbitMq或类似的),并创build一个消耗队列中asynchronous消息的worker。