【问题标题】:Can't set headers after they are sent error. I am not calling render()/json() twice发送错误后无法设置标头。我没有调用 render()/json() 两次
【发布时间】:2016-01-20 22:01:11
【问题描述】:

在向数据库输入条目后,我试图向客户端返回响应。我已经编写了以下代码来实现所需的结果,但是我得到了

错误:发送后无法设置标头。

我不会在任何地方为该响应调用 response.json()response.render() 两次。那么为什么会出现这个错误呢?

router.post('/yolo', jsonParser, function(req, res, next) {

    response = res;
    shortUrl = shortenTheUrl(req.body.textBoxValue);
    var insertDataInTableQuery = "INSERT INTO `WinGoku`.`ShortenedUrlsTable` (`OriginalUrl`, `ShortUrl`) VALUES('"+req.body.textBoxValue+ "', '"+ shortUrl +"')";
    runSQLQuery(insertDataInTableQuery, sendResponseToClient);
});

function runSQLQuery(query, callbackFunction) {
    connection.query(query, function(error) {
        if(error) {
            console.log(query);
            console.log("QueryError: "+ error);
            if(callbackFunction != undefined)
                callbackFunction({type: "alert", errorMessage: error});
        }

        if(callbackFunction != undefined)
            callbackFunction({type: "alert", errorMessage: "successful"});
    });
}

function sendResponseToClient(queryExecutionResult) {
    console.log("1: "+ queryExecutionResult["type"] + " 2: "+ queryExecutionResult["errorMessage"]);
    response.json({shortenedUrl: shortUrl, type: queryExecutionResult["type"], message: queryExecutionResult["errorMessage"]});
            ^
            error here. Can't set headers after they are sent
}

【问题讨论】:

  • runSQLQuery发生错误时,回调会被调用两次。顺便说一句,您的代码似乎容易受到SQL injections 的影响。

标签: javascript jquery node.js express


【解决方案1】:

您可能会调用 response.json() 两次,如果查询失败并且不是从错误子句返回,它也会执行查询成功子句。因此,您必须在错误子句的末尾放置一个返回语句。这应该可以解决问题。

function runSQLQuery(query, callbackFunction) {
    connection.query(query, function(error) {
        if(error) {
            console.log(query);
            console.log("QueryError: "+ error);
            if(callbackFunction != undefined)
                callbackFunction({type: "alert", errorMessage: error});

            return; // this should fix the problem!
        }

        if(callbackFunction != undefined)
            callbackFunction({type: "alert", errorMessage: "successful"});
    });
}

【讨论】:

  • 不仅如此,response 还是一个全局变量 (!)。即使没有错误,也可能会出现在同一响应对象上多次调用 response.json() 的情况。
【解决方案2】:

您没有结束响应,因此错误即将到来。 尝试像这样修改您的代码:

router.post('/yolo', jsonParser, function(req, res, next) {
    response = res;
    shortUrl = shortenTheUrl(req.body.textBoxValue);
    var insertDataInTableQuery = "INSERT INTO `WinGoku`.`ShortenedUrlsTable` (`OriginalUrl`, `ShortUrl`) VALUES('"+req.body.textBoxValue+ "', '"+ shortUrl +"')";
    runSQLQuery(insertDataInTableQuery, sendResponseToClient, function(data){
     res.end();
    });
});

【讨论】:

  • runSQLQuery() 接受两个参数,而不是三个。
  • 添加 runSQLQuery(query, callbackFunction, success) {} 然后检查方法是否完成。
猜你喜欢
  • 2019-03-26
  • 2018-06-08
  • 2018-06-29
  • 2013-12-22
  • 1970-01-01
  • 1970-01-01
  • 2017-03-31
相关资源
最近更新 更多