NodeJS Express MySQL发布请求抛出"无法在将标头发送到客户端之后设置标头"

时间:2018-02-18 22:15:12

标签: mysql node.js express promise

我尝试通过快速发布请求发回一些MySQL结果,但无论我尝试什么,都会出现以下错误:

(node:3743) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at validateHeader (_http_outgoing.js:503:11)
    at ServerResponse.setHeader (_http_outgoing.js:510:3)
    at ServerResponse.header (/home/dvs23/projects/Group/Visualizer/node_modules/express/lib/response.js:767:10)
    at ServerResponse.send (/home/dvs23/projects/Group/Visualizer/node_modules/express/lib/response.js:170:12)
    at ServerResponse.json (/home/dvs23/projects/Group/Visualizer/node_modules/express/lib/response.js:267:15)
    at ServerResponse.send (/home/dvs23/projects/Group/Visualizer/node_modules/express/lib/response.js:158:21)
    at /home/dvs23/projects/Group/Visualizer/index.js:193:11
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:160:7)
(node:3743) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:3743) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

代码的重要部分是:

app.post('/getNews', (req, res) => {
  var prom = new Promise(function(resolve, reject) {
      //create nodes for result
      con.connect(function() {
        console.log("Connected!");
        con.query("SELECT ID,length(Text) FROM news;", function(err, result, fields) {
          if (err) {
            console.log(err);
            reject(err);
            return;
          }

          var nodesArr = [];
          result.forEach((row) => {
            nodesArr.push({
              "id": row["ID"],
              "size": row["length(Text)"]
            });
          });

          con.query("SELECT * FROM newsSim;", function(err, result2, fields) {
            if (err){
              console.log(err);
              reject(err);
              return;
            }

            var linksArr = [];
            result2.forEach((row) => {
              linksArr.push({
                "source": row["TID1"],
                "target": row["TID2"],
                "value": row["SIM"]
              });
            });
            console.log({
              "nodes": nodesArr,
              "links": linksArr
            });
            resolve({
              "nodes": nodesArr,
              "links": linksArr
            });
          });
        });
      });
    })
    .then(function(result) {
      console.log(result);
      res.send(result); //send result to client
    }, function(err) {
      console.log("END"+err);
      res.send({
        "nodes": [],
        "links": []
      });
    });
});

App是我的express-app,请求来自静态HTML页面,也是由NodeJS服务器通过jQuery提供的。 我已经使用了一个承诺,那么怎么可能发送已被调用? 也没有承诺,只有嵌套查询,同样的错误(显然没有UnhandledPromiseRejectionWarning的东西)。

编辑:

嵌套的MySQL查询没有问题,即使以下内容也不起作用:

app.post('/getNews', (req, res) => {
  //var text = req.fields["text"];

  var prom = new Promise(function(resolve, reject) {
      //create nodes for result
      con.connect(function() {
        console.log("Connected!");
        con.query("SELECT ID,length(Text) FROM news;", function(err, result, fields) {
          if (err) {
            console.log(err);
            reject(err);
            return;
          }

          var nodesArr = [];
          result.forEach((row) => {
            nodesArr.push({
              "id": row["ID"],
              "size": row["length(Text)"]
            });
          });

          resolve(nodesArr);
          return;
        });
      });
    })
    .then(function(news) {
      console.log(news);
      //if (res.headersSent) return;
      res.send(news); //send result to client
    }, function(err) {
      console.log("END"+err);
      //if (res.headersSent) return;
      res.send({
        "nodes": [],
        "links": []
      });
    });
});

如果我使用if(res.headersSent),则不会将任何内容发送回我的网站,既不是空结果,也不是根据需要获取的实际结果 - &gt;我可以将它记录到控制台......

EDIT2:

app.post('/getNews', (req, res) => {
  //var text = req.fields["text"];
  req.connection.setTimeout(6000000, function () { 
    console.log("Timeout 2");
    res.status(500).end(); 
  });

  var prom = new Promise(function(resolve, reject) {
      //create nodes for result
      con.connect(function() {
        console.log("Connected!");
        con.query("SELECT ID,length(Text) FROM news;", function(err, result, fields) {
          if (err) {
            console.log(err);
            reject(err);
            return;
          }

          var nodesArr = [];
          result.forEach((row) => {
            nodesArr.push({
              "id": row["ID"],
              "size": row["length(Text)"]
            });
          });

          con.query("SELECT * FROM newsSim;", function(err2, result2, fields2) {
            if (err2){
              console.log(err2);
              reject(err2);
              return;
            }

            var linksArr = [];
            result2.forEach((row) => {
              linksArr.push({
                "source": row["TID1"],
                "target": row["TID2"],
                "value": row["SIM"]
              });
            });
            resolve({
              "nodes": nodesArr,
              "links": linksArr
            });
            return;
          });
        });
      });
    })
    .then(function(news) {
      //if (res.headersSent) return;
      res.send(news); //send result to client
      console.log(news);
    }, function(err) {
      console.log("END"+err);
      //if (res.headersSent) return;
      res.send({
        "nodes": [],
        "links": []
      });
    });
});

尝试设置超时,但现在错误发生 之前调用超时回调...

(node:9926) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at validateHeader (_http_outgoing.js:503:11)
    at ServerResponse.setHeader (_http_outgoing.js:510:3)
    at ServerResponse.header (/home/dvs23/projects/Group/Visualizer/node_modules/express/lib/response.js:767:10)
    at ServerResponse.send (/home/dvs23/projects/Group/Visualizer/node_modules/express/lib/response.js:170:12)
    at ServerResponse.json (/home/dvs23/projects/Group/Visualizer/node_modules/express/lib/response.js:267:15)
    at ServerResponse.send (/home/dvs23/projects/Group/Visualizer/node_modules/express/lib/response.js:158:21)
    at /home/dvs23/projects/Group/Visualizer/index.js:198:11
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:160:7)
(node:9926) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:9926) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Timeout 2

1 个答案:

答案 0 :(得分:1)

不要问我为什么,但它现在似乎有效......可能按照oniramarf的建议设置一个特定的超时是关键。还添加了

multipleStatements: true   

到mysql.createConnection(...)并将静态内容移动到不同的路径:

app.use('/site', express.static('static'));

但这可能不是它现在起作用的原因:)

代码:

app.post('/getNews', (req, res) => {
  //var text = req.fields["text"];

  var prom = new Promise(function(resolve, reject) {
      //create nodes for result
      con.connect(function() {
        console.log("Connected!");
        con.query("SELECT ID,length(Text) from news;", function(err, result, fields) { //SELECT ID,length(Text) FROM news;
          if (err) {
            console.log(err);
            reject(err);
            return;
          }

          con.query("SELECT * FROM newsSim;", function(err2, result2, fields2) {
            if (err2) {
              console.log(err2);
              reject(err2);
              return;
            }

            var imporIDs = new Set();

            var linksArr = [];
            result2.forEach((row) => {
              if (row["SIM"] > 0.25) {
                imporIDs.add(row["TID1"]);
                imporIDs.add(row["TID2"]);
                linksArr.push({
                  "source": row["TID1"],
                  "target": row["TID2"],
                  "value": row["SIM"]
                });
              }
            });

            var nodesArr = [];
            result.forEach((row) => {
              if (imporIDs.has(row["ID"])){
                nodesArr.push({
                  "id": row["ID"],
                  "size": row["length(Text)"]
                });
              }
            });
            resolve({
              "nodes": nodesArr,
              "links": linksArr
            });
            return;
          });
        });
      });
    })
    .then(function(news) {
      //if (res.headersSent) return;
      res.send(news); //send result to client
      console.log(news);
    }, function(err) {
      console.log("END" + err);
      //if (res.headersSent) return;
      res.send({
        "nodes": [],
        "links": []
      });
    });
});

var server = http.createServer(app);

server.listen(8080, function() {
  console.log('localhost:8080!');
});
server.timeout = 120000;

编辑:
真的好像是超时,经过一些更改再次发生错误,所以我设置server.timeout = 12000000再次工作:)