Vikas Kumar Vikas Kumar - 1 month ago 7
MySQL Question

Why doesn't this code return json data?

I'm trying to fetch data from database using Node.js and MySQL.

Here's what I'm trying:

var app=require('express')();
var bodyParser=require("body-parser");
var mysql=require('mysql');
var http=require('http');
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end();
}).listen(8081);
console.log('Server running at http://127.0.0.1:8081/');
var connection=mysql.createConnection({
host: 'localhost',
user: 'root',
password: "",
database: 'books'
});
connection.connect(function(err) {
if ( !err ) {
console.log("Connected to MySQL");
} else if ( err ) {
console.log(err);
}
});
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.get('/book', function(req, res){
var data={
'error': 1,
'Books': ""
};
connection.query("SELECT * FROM book", function(err, rows, fields){
if(rows.length!=0){
data['error']=0;
data['Books']=rows;
res.json(data);
}else{
data['Books']='No books found';
res.json(data);
}
});
});


When I execute
node server.js
it shows following output in the cmd:

Server running at http://127.0.0.1:8081/
Connected to MySQL


But when I visit to http://127.0.0.1:8081/book, it doesn't display any output.

NOTE: My XAMPP Apache server and MySQL are started.

Answer

The problem is, I believe, that you're using two different and redundant web servers. One is http and the other is app (ie. Express). Only http is actually listening on port 8081.

http.createServer(function (request, response) {
    response.writeHead(200, {'Content-Type': 'text/plain'});
    response.end();
}).listen(8081);

Since all it ever does is write a text/plain header and exit you'll get a blank page no matter what path you try to access.

The other one, app, never listens on a port. So all that app code sets up a server that can't be accessed.

So remove all the http stuff, you don't need it. Express handles this for you. Then call app.listen(8081).

var app        = require('express')();
var bodyParser = require("body-parser");
var mysql      = require('mysql');

var connection=mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: "",
    database: 'books'
});

connection.connect(function(err) {
    if ( !err ) {
        console.log("Connected to MySQL");
    } else if ( err ) {
        console.log(err);
    }
});

app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());

app.get('/book', function(req, res){
    var data={
        'error': 1,
        'Books': ""
    };
    connection.query("SELECT * FROM book", function(err, rows, fields){
        if(rows.length!=0){
            data['error']=0;
            data['Books']=rows;
            res.json(data);
        }else{
            data['Books']='No books found';
            res.json(data);
        }
    });
});

app.listen(8081, function () {
    console.log('Server running on port 8081');
});
Comments