Node.js表示超时“发送后无法设置标头". [英] Node.js express, timeout "Can\'t set headers after they are sent."

查看:57
本文介绍了Node.js表示超时“发送后无法设置标头".的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

nodejs和express有一些非常奇怪的问题.

I have some really strange problem with nodejs and express.

我处理请求的功能之一,必须从数据库中获取某些内容并将其作为JSON发送到客户端.

One of my functions that handles request, have to get something from DB and send it as JSON to client.

它是这样的:

  1. 获取请求
  2. 致电数据库
  3. 处理数据并将其打包为JSON
  4. response.json(JSON)

通常情况下一切正常,但是如果2到3之间存在超时(因为它是异步的),它将自动创建响应,并且会出现错误在发送标头后无法设置标头".当我打电话给4

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

还有其他人有这个问题吗?有什么正常的方法可以处理它,还是我只需要检查response._header是否已设置好?

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);
    });
};

AppTime.getByGroupId内部具有异步调用.

And AppTime.getByGroupId has asynchronous call inside.

推荐答案

好的,问题是多部分表单数据处理超时.

Ok, problem is multipart-form-data handling timeout.

发生这种情况时,它将调用next(err).

When that happens it calls next(err).

  form.on('error', function(err){
    if (!options.defer) {
      err.status = 400;
      next(err);
    }
    done = true;
  });

默认情况下,发生错误时它将执行res.send(400),并且在正常情况下获取要执行的代码时会出现问题.

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.

这篇关于Node.js表示超时“发送后无法设置标头".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆