[英]How to display Data from MySQL database in Node.js in browser
I want to display DB data in my browser .. my file connection.js is我想在我的浏览器中显示数据库数据..我的文件 connection.js 是
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;
and my app.js is :我的 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}/`);
});
Error : throw er;错误:抛出错误; // Unhandled 'error' event,,,, Error [ERR_STREAM_WRITE_AFTER_END]: write after end
// 未处理的 'error' 事件,,,, Error [ERR_STREAM_WRITE_AFTER_END]: write after end
You must only write your responses to the client from within the callback function of mysql.query()
.您只能在
mysql.query()
的回调函数mysql.query()
您的响应写入客户端。
In other words, your program runs these two lines immediately换句话说,你的程序会立即运行这两行
res.write('Hello World'); //write a response to the client
res.end(); //end the response
before MySQL gets its data the callback runs.在 MySQL 获取其数据之前,回调运行。 Your
res.end()
ends the output.您的
res.end()
结束输出。 Therefore, later, when the callback runs, it tries to res.write()
to an already ended stream.因此,稍后,当回调运行时,它会尝试将
res.write()
写入已经结束的流。
So move those two lines to within your callback.因此,将这两行移到您的回调中。 Try this
尝试这个
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
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.