gpt4 book ai didi

javascript - 发送错误后无法设置 header 。我没有调用 render()/json() 两次

转载 作者:行者123 更新时间:2023-12-03 07:53:28 28 4
gpt4 key购买 nike

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

错误:发送后无法设置 header 。

我不会在任何地方为此响应调用两次 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
}

最佳答案

您可能会调用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"});
});
}

关于javascript - 发送错误后无法设置 header 。我没有调用 render()/json() 两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34900770/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com