问题
I have some really strange problem with nodejs and express.
One of my functions that handles request, have to get something from DB and send it as JSON to client.
So it goes like this:
- Get request
- Call DB
- Process data and pack it to JSON
- response.json(JSON)
Normally it will go all OK but if there is timeout between 2 and 3 because it is asynchronously it will automatically create response and there will be error "Can\'t set headers after they are sent." when I call 4
Does anyone else have this problem? Is there any normal way to handle it or I just have to check if response._header is allready set?
exports.appstimebygroup = function (req, res) {
var resp = {};
var clientId = Webapi.extractClientId(req);
AppTime.getByGroupId(clientId, req.body.groupId, function(error, appstime){
if (error) {
handleError(error);
resp.returnCode = 0;
resp.message = "Some error have happened, please contact support!";
res.setHeader("Content-Type", "application/json");
res.json(resp);
return;
}
resp.returnCode = 1;
resp.appstime = appstime;
if(res._header){
console.log("header allready set!");
return;
}
res.setHeader("Content-Type", "application/json");
res.json(resp);
});
};
And AppTime.getByGroupId has asynchronous call inside.
回答1:
Ok, problem is multipart-form-data handling timeout.
When that happens it calls next(err).
form.on('error', function(err){
if (!options.defer) {
err.status = 400;
next(err);
}
done = true;
});
By default on error it will do res.send(400) and when normally gets to code that you wanted to be executed there is problem.
来源:https://stackoverflow.com/questions/26262745/node-js-express-timeout-can-t-set-headers-after-they-are-sent