Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/36.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在浏览器Node.js中显示MySQL数据库中的数据_Mysql_Node.js - Fatal编程技术网

如何在浏览器Node.js中显示MySQL数据库中的数据

如何在浏览器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

我想在浏览器中显示DB数据。。 我的文件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}/`);
});
错误:抛出器;//未处理的“错误”事件,,,,
错误[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(结果)中工作;