如何在浏览器Node.js中显示MySQL数据库中的数据
我想在浏览器中显示DB数据。。 我的文件connection.js是如何在浏览器Node.js中显示MySQL数据库中的数据,mysql,node.js,Mysql,Node.js,我想在浏览器中显示DB数据。。 我的文件connection.js是 var mysql = require('mysql'); var conn = mysql.createConnection({ host: "localhost", user: "root", password: "0000", database: "select_country" }); conn.conne
var mysql = require('mysql');
var conn = mysql.createConnection({
host: "localhost",
user: "root",
password: "0000",
database: "select_country"
});
conn.connect(function (err) {
if (err) throw err;
console.log('Database is connected successfully ??????!');
});
module.exports = conn;
我的app.js是:
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const mysql = require('./MySql/database');
//create a server object:
const server = http.createServer(function (req, res) {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
mysql.query("SELECT * FROM country", function (err, result, fields) {
if (err) throw err;
console.log('All Countries are :-');
res.write(result); //write a response to the client
});
res.write('Hello World'); //write a response to the client
res.end(); //end the response
}); //the server object listens on port 8080
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
错误:抛出器;//未处理的“错误”事件,,,,
错误[ERR\u STREAM\u WRITE\u AFTER\u END]:结束后写入您只能从
mysql.query()
的回调函数中向客户端写入响应
换句话说,您的程序立即运行这两行
res.write('Hello World'); //write a response to the client
res.end(); //end the response
在MySQL获取数据之前,回调将运行。您的res.end()
结束输出。因此,稍后,当回调运行时,它会尝试将res.write()
写入已结束的流
因此,将这两行移到回调中。试试这个
mysql.query("SELECT * FROM country", function (err, result, fields) {
if (err) throw err;
res.write('Hello World'); //write a response to the client
console.log('All Countries are :-');
res.write(result); //write a response to the client
res.end(); //end the response
});
抛出错误;//重新显示非MySQL错误。。如果我执行console.log(结果);工作很好。。但不在res.write(结果)中工作;