当我连接到MySQL时,Nodejs无法加载页面?
我可以毫无问题地在node.js上运行其他程序。当我想通过NODE.js连接到MySQL时,当我在终端和当我连接到MySQL时,Nodejs无法加载页面?,mysql,node.js,Mysql,Node.js,我可以毫无问题地在node.js上运行其他程序。当我想通过NODE.js连接到MySQL时,当我在终端和http://localhost:8080/在浏览器中 我的代码如下: // Include http module, var http = require('http'), // And mysql module you've just installed. mysql = require("mysql"); // Create the connection. // Data is
http://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);
NB:MySQL连接是正确的,因为我通过PHP连接到数据库没有问题。
NB:在我的js文件旁边有一个名为node\u modules
的文件夹,里面有mysql文件夹。
我试图通过npm安装nodejs:
A请求
仅在响应已发送时结束
您正在等待end
事件,但从未发送响应(因为该响应是从end
处理程序中发送的,导致某种死锁情况)
正如@vkurchatkin在评论中指出的那样,如果请求流正在被消费,那么一旦它被完全消费,将调用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));
});
});
当我转到URL时,它会打开下载窗口。我认为标头无法识别。请尝试
application/json
,这是json数据的正确内容类型。“只有在发送响应后,请求才会结束。”-在all@vkurchatkin试图简化这里的事情。我没有详细说明请求何时结束。请随意提出备选方案,我会更新我的答案。由于streams1与streams2的不同,此主题会不时弹出。以下是我对其中一个问题的回答: