Tomhans.J
Tomhans.J

Reputation: 440

How to get data from nodejs from sql and return json?

I'm new to js. Recently I want to implement a feature, there's a button on the page to get data, click Access database after data showing on the page, the database with MySQL server are using nodejs to build, how to write it with nodejs.

XML/HTML code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
<button>get</button>
<!-- show data -->
<div id="res"></div>
</body>
<script src="node_getdata.js"></script>
</html>

JavaScript code

var http = require("http");
var mysql = require("mysql");

var conn = mysql.createConnection({
    host : "localhost",
    user : "root",
    password : "",
    database : "test"
});

conn.connect();

conn.query("select * from person", function(err,results){
    if(err){
        console.log(err);
        return;
    }

    console.log("Result", results);
});

Upvotes: 4

Views: 23528

Answers (1)

piotrbienias
piotrbienias

Reputation: 7401

You can create a web server with use of Express framework, which could look like that (very simple example):

var express = require('express');
var app = express();

var mysql = require('mysql');

var conn = mysql.createConnection({
    host : 'localhost',
    user : 'root',
    password : '',
    database : 'test'
});

conn.connect();

app.get('/test', function(request, response){
    conn.query('select * from persons', function(error, results){
        if ( error ){
            response.status(400).send('Error in database operation');
        } else {
            response.send(results);
        }
    });
});

app.listen(3000, function () {
    console.log('Express server is listening on port 3000');
});

Of course you should transform the result of the database operation, probably to some JSON format in order to obtain it in readable form.

Then, you can simply call your REST api with use of XMLHhttpRequest if you want to use plain Javascript.

function getPersons() {
    var xmlHttpRequest = new XMLHttpRequest();

    xmlHttpRequest.onreadystatechange = function() {
        if ( xmlHttpRequest.readyState == XMLHttpRequest.DONE && xmlHttpRequest.status == 200 ) {
            document.getElementById("persons").innerHTML = xmlHttpRequest.responseText;
        }
    };
    xmlHttpRequest.open('GET', 'http://localhost/test', true);
    xmlHttpRequest.send();
}

And, in order to perform the HTTP call, you can define a button with onClick event:

<button type='button' onclick='getPersons()'>Get persons!</button>

Upvotes: 10

Related Questions