2015-09-28 98 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

感謝。這項工作 –