簡體   English   中英

如何在瀏覽器中的 Node.js 中顯示 MySQL 數據庫中的數據

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM