node.js + MySQL & JSON-result - Callback-issue & no response to client

后端 未结 1 638
我在风中等你
我在风中等你 2021-02-13 11:06

I\'d like to use node.js to query a mySQL-database and return the results as JSON to be used in a mobile application. Unfortunately, my request just sorta times out and the serv

1条回答
  •  余生分开走
    2021-02-13 12:12

    You're following an older guide which instructs you to wait for the request's close event before sending the response, but you actually no longer need to do that.

    What's happening is you aren't sending your response, so your client is timing out. Only until the client times out is when close events fires. Since the client has disconnected by the time you send your response, you don't get anything on the client and only see it in the terminal.

    To fix this problem, just stop waiting for the close event and run code immediately when the request handler is called:

    var http = require('http');
    http.createServer(function(req, res) {
      getSQL(function(err, result) {
        res.writeHead(200, {
          'Content-Type' : 'x-application/json'
        });
        res.end(result);
      });
    }).listen(3000);
    

    0 讨论(0)
提交回复
热议问题