简体   繁体   中英

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

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 :

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

You must only write your responses to the client from within the callback function of 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. Your res.end() ends the output. Therefore, later, when the callback runs, it tries to res.write() to an already ended stream.

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
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM