当我连接到MySQL时Nodejs无法加载页面?

我可以在node.js上运行其他程序,没有任何问题。 当我想通过NODE.js连接到MySQL时,当我在terminal中inputnodejs mysqlConnection.js并在浏览器中inputhttp://localhost:8080/时,它会永久加载。

我的代码如下:

 // Include http module, var http = require('http'), // And mysql module you've just installed. mysql = require("mysql"); // Create the connection. // Data is default to new mysql installation and should be changed according to your configuration. var connection = mysql.createConnection({ user: "root", password: "", database: "framework" }); // Create the http server. http.createServer(function (request, response) { // Attach listener on end event. request.on('end', function () { // Query the database. connection.query('SELECT * FROM words;', function (error, rows, fields) { response.writeHead(200, { 'Content-Type': 'x-application/json' }); // Send data as JSON string. // Rows variable holds the result of the query. response.end(JSON.stringify(rows)); }); }); // Listen on the 8080 port. }).listen(8080); 

注意:MySQL连接是正确的,因为我通过PHP连接到我的数据库没有问题。

注意:我有一个名为node_modules的文件夹,位于我的js文件旁边,里面有mysql文件夹。

我试图通过npm来安装nodejs:

在这里输入图像说明

一个request只有在响应被发送时才结束

您正在等待end事件而没有发送响应(因为响应是从end处理程序发送的,导致了一种死锁情况)。

正如@vkurchatkin在注释中指出的那样,如果请求stream正在被使用,那end处理程序一旦完全被使用就会被调用,而与响应的状态无关。 在这种情况下,请求根本没有被使用,这意味着只有在响应被发送之后, end处理程序才会被调用(可能是作为请求的一部分)。

所以完全删除end处理程序应该解决这个问题:

 http.createServer(function (request, response) { connection.query(..., function(error, rows, fields) { // TODO: handle `error` response.writeHead(200, { 'Content-Type': 'x-application/json' }); response.end(JSON.stringify(rows)); }); });