Example 3: Restful API

This example will show you how to create a Node.js Restful API for the backend, and it will be called by the frontend – AngularJS. The Node.js Restful API will response with JSON output to AngularJS frontend. You will find that it is so simple to do so.

You will find that the folder structure and required JS files are similar to example 2. Let’s try create some folders:

example under {your_node.js_installed_path}\nodejs\
demo3 under {your_node.js_installed_path}\nodejs\examples\
app under {your_node.js_installed_path}\nodejs\examples\demo3\app\
controllers under {your_node.js_installed_path}\nodejs\examples\demo3\app\controllers\
models under {your_node.js_installed_path}\nodejs\examples\demo3\app\models\
config under {your_node.js_installed_path}\nodejs\examples\demo3\config\
log under {your_node.js_installed_path}\nodejs\examples\demo3\log\

 

Then, create a js file “app.js” under {your_node.js_installed_path}\nodejs\examples\demo3\ with below codes. It is entry point of demo3 application, and sets the global configures here. In fact, it is the same as example 2 ‘s app.js file.

//Declare required library

var express                                         = require(‘express’);

var bodyParser                                 = require(‘body-parser’);

var path                                               = require(‘path’);

var fs                                                     = require(‘fs’);

var morgan                                         = require(‘morgan’);

var FileStreamRotator                    = require(‘file-stream-rotator’);

var db                                                   = require(‘./config/db’);

 

var app = express();

var logFolder = __dirname + ‘/log’;

 

fs.existsSync(logFolder) || fs.mkdirSync(logFolder);

 

//Logger details

var logFileStream = FileStreamRotator.getStream({

date_format:   ‘YYYY-MM-DD’,

filename:           logFolder + ‘/demo3_%DATE%.log’,

frequency:        ‘daily’,

verbose:                            false

});

 

//Setup app variables

app.set(‘port’, 3000);

 

app.use(morgan(‘combined’, {stream: logFileStream}));

app.use(bodyParser.json());

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

 

//Setup the routes

app.use(require(‘./app/controllers’));

 

//Setup Listener with Port app.get(‘port’)

app.listen(app.get(‘port’), function () {

console.log(‘Demo 3 listening on port ‘ + app.get(‘port’));

});

 

Under {your_node.js_installed_path}\nodejs\examples\demo3\config\ , please create the database configuration file db.js as below. Again, it is the same as example 3 ‘s db.js file.

//Declare MySQL library

var mysql = require(‘mysql’);

//Declare MySQL connection pool

var pool =  mysql.createPool({

  host:                      ‘localhost’,

                user:                      ‘root’,

                password:           ‘root’,

                database:            ‘itblogs’,

                port:                      3306

});

 

//Running select SQL

exports.runQuery = function(query,callback) {

//Making Query

pool.getConnection(function(err, connection){

connection.query( query, function(err, rows){

if(err)    {

throw err;

}else{

console.log( query );

callback(rows);

}

});

connection.release();

});

};

 

//Running insert,update,delete SQL

exports.runSQL = function(sql,callback) {

//Making Query

pool.getConnection(function(err, connection){

connection.query( sql, function(err){

if(err)    {

console.log( sql + ‘ ::: ‘ + err );

callback(false);

}else{

console.log( sql );

callback(true);

}

});

connection.release();

});

};

 

Please note that you may need to update the MySQL database connection username and password for your MySQL server:

var conn = mysql.createConnection({

    host:                      ‘localhost’,

                                user:                      ‘root’,

                                password:           ‘root’,

                                database:            ‘itblogs’,

                                port:                      3306

});

 

As this example will demonstrate MVC framework, let’s create the framework layer by layer.

A. Controllers

Please download here and store the codes under {your_node.js_installed_path}\nodejs\examples\demo3\app\controllers\

You can find the business logic in this layer

B. Models

Please download here and store the codes under {your_node.js_installed_path}\nodejs\examples\demo3\app\models\

You can find the models here.

 

Ok, everything is ready now. Let’s try to run the application and see what’s happening. You can:

  1. run “cmd”
  2. cd {your_node.js_installed_path}\nodejs\
  3. node examples/demo3/app.js

 

Then, open with a browser (http://localhost:3000), you should find the below page.

 

Let’s try this URL : http://localhost:3000/shop

 

Cross Domain Error

You may share your Restful API to other server(s), crossing different domains. Browsers may not allow access to other domains’ restful API. In order to fix this problem, we need to add the below codes to our controllers:

//To allow cross-domain request from port 8080

router.use(function(req, res, next) {

res.header(‘Access-Control-Allow-Origin’, ‘http://localhost:8080’);

res.header(‘Access-Control-Allow-Methods’, ‘GET,PUT,POST,DELETE,OPTIONS’);

res.header(‘Access-Control-Max-Age’, 3600);

res.header(‘Access-Control-Allow-Headers’, ‘X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept’);

next();});

 

The node.js Restful API is done, you can find the next article for AngularJS web CRUD frontend UI.

Please rate this