[英]How can we get data from mysql database in angular 7 application by using node.js and display it on angular component html page
[英]How to display Data from MySQL database in Node.js in browser
我想在我的浏览器中显示数据库数据..我的文件 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;
我的 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' 事件,,,, Error [ERR_STREAM_WRITE_AFTER_END]: write after end
您只能在mysql.query()
的回调函数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
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.