简体   繁体   中英

Node-JS Expose Mysql DB as Rest Service

I am very new to NodeJs and struggling to frame an Approach here

We are building an Application with Oracle JET (javascript Framework) and we have Mysql databases as backend for our Application

My task is to Create REST API from Mysql using NODEJS

As a Beginner how should I approach this ?

What topics to be learned in Node js to do this?

Can Stored Procedures also be exposed as an Rest API?

Any help

Thanks

It's fairly simple to return mysql results using Express, it doesn't take many lines of code:

 const express = require("express");
const mysql   = require('mysql');

const connection = mysql.createConnection({
    host     : 'localhost',
    user     : 'root',
    password : 'root',
    database : 'my_db'
});

connection.connect((err) => {
     if(err) {
         console.error("Error connecting to db: ", err); 
     } else {
         console.log("Connected to db successfully"); 
     }
});

const app = express();

app.get("/users", (req,res) => {

    connection.query('SELECT * FROM Users', (err, rows, fields) => {

        if (err) {
            console.error('Error while performing query: ', err);
        } else {
            console.log('Result: ', rows);
            // Send to caller as json
            res.json(rows);
        }

    });
});

// Call Stored Proc 'GetUsers'
app.get("/get_users", (req,res) => {

    connection.query('CALL GetUsers()', (err, rows, fields) => {

        if (err) {
            console.error('Error while performing query: ', err);
        } else {
            console.log('Result: ', rows);
            // Send to caller as json
            res.json(rows);
        }

    });
});

app.listen(3000);

You can query using Curl (or your browser) by going to http://localhost:3000/users , eg

curl http://localhost:3000/users

You'd get a result like this:

[{
    "firstName": "Craig",
    "lastName": "Michaels"
},
{
    "firstName": "Jim",
    "lastName": "Thomson"
},
{
    "firstName": "Abigail",
    "lastName": "Moore"
}]

I've added a path /get_users that calls a GetUsers() stored procedure (defined as below):

DROP PROCEDURE IF EXISTS GetUsers; 
DELIMITER // 
CREATE PROCEDURE GetUsers() 
BEGIN 
    SELECT * from Users ;
END // 
DELIMITER ;

The Table Users is like so:

create table users ( firstName varchar(100), lastName varchar(100)  );

We can call this via:

curl http://localhost:3000/get_users

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