I have a Node.js Express server to which I send a response, and then try to do more processing with the same request instance.
If I write to res after sending the headers, I get an error, but what happens if I use a req-readable stream after sending a response to the corresponding answer?
In other words, how can I send an HTTP response with a Node server before I finish processing the entire request?
In other words, if I have already sent a response, how can I “destroy” a request after it has already sent a response - is there really anything to do but send a response?
At the moment, it seems that there are some strange errors associated with using the request object (stream), which corresponds to the response that has already been sent.
Let me give you some examples with code-
Below are the last 3 Express middleware handlers on my server. As one interesting side-element - as soon as one intermediate code handler is called for the request, it cannot be re-reused (it looks like this). So what happens is that the first handler below is called when the response is sent. Then another execution path (using process.nextTick or setImmediate) calls next (), and two second handlers are called, which means that I get 404 registered on my server.
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();
}
});
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
}
});
}
}
});