Node.js express, timeout “Can\'t set headers after they are sent.”

徘徊边缘 提交于 2020-01-03 04:53:24

问题


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:

  1. Get request
  2. Call DB
  3. Process data and pack it to JSON
  4. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!