0

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

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

throw err; // Rethrow non-MySQL errors.. if i do console.log(result); it's work fine .. but not working in res.write(result);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.