2015-09-28 110 views
1

我无法理解用Sql和node.js。 文件app.js:NodeJS + MySql请求

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(); 

}); 

后,我到/ API说话,因为它发生在开始页面。在控制台中,我看到了来自基地的响应。但浏览器只是挂出如何得到正常byzy的响应,并立即关闭连接?谢谢。

回答

-1

您没有发送任何响应,这就是浏览器正在等待的原因。

添加

res.end(); 

connection.end(); 

全码:

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(); 

}); 
+0

感谢。这项工作 –