简体   繁体   中英

NodeJS + MySql request

I can not understand With Sql and node.js. a file app.js:

var connection = mysql.createConnection ({
   host: 'localhost',
   user: 'root',
   password: '',
   database: "messenger"
});

var app = express ();

app.get ('/ api', function (req, res, next) {

   connection.connect ();
   connection.query ('SELECT * FROM user_contacts AS uc INNER JOIN users AS u ON u.id = uc.contact_user_id WHERE uc.user_id = 1', function (err, rows, fields) {
     if (err) throw err;
     console.log (rows);
   });
   connection.end ();

});

After I speak to / API as it happens at the start page. In the console, I see a response from the base. But the browser just hangs out how to get a response from the normal byzy and immediately close the concatenate? Thank you.

You are not sending any response, that is why the browser is waiting.

Add

res.end();

after

connection.end();

Full code:

app.get ('/ api', function (req, res, next) {

   connection.connect ();
   connection.query ('SELECT * FROM user_contacts AS uc INNER JOIN users AS u ON u.id = uc.contact_user_id WHERE uc.user_id = 1', function (err, rows, fields) {
     if (err) throw err;
     console.log (rows);
   });
   connection.end ();
   res.end();

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM