Build Up The Node App Structure
Following the node express folder architecture to build the RESTful API.
|___package.json
|
|___app.js
|
|___controller
| |__index.js
| |__users.js
|
|___models
| |__users
| |__signup.js
# Node Express 4
Let us see how to create RESTful APIs for user registration using Node.js and Express. Using Node Express we can easily manage GET, POST, PUT, DELETE requests.
In this following tutorials, we will see the POST method, which will store the user’s details into the database using the RESTful API
Install Dependencies
Let’s start with the following dependencies related.
Will going to use following node modules for handling session :
- Node Express 4
- Body parser
- MySql
Install dependencies through the following command.
$ npm install
{
"name": "expapp",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"dependencies": {
"async": "^1.5.2",
"body-parser": "^1.14.1",
"express": "^4.13.3",
"express-session": "^1.12.1",
"http-proxy": "^1.12.0",
"mysql": "^2.9.0",
"node-mysql": "^0.4.2",
}
}
Initialization & Require
First will include require node modules. Also, do connection of MySql for POST data.
SEE : Connect Mysql database in NodeJS here
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var session = require('express-session');
var db = require('./models/db.js');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));// Body parser use JSON data
if(GLOBAL.SQLpool === undefined){
GLOBAL.SQLpool = db.createPool(); //create a global sql pool connection
}
app.use(require('./controllers'));
app.listen('3000', function(){
console.log("Connected on port 3000.");
});
Controller Directory
The controller defines your app routes and their logic. Controllers will handle web requests, serve your templates to the user and interact with your models to process and retrieve data. It’s the glue which connects and controls your web application.
Controller index file control all the in the current directory and export to the models.
var express = require('express')
, router = express.Router();
router.use('/api/users', require('./users'));
module.exports = router;
Where the /controller/users.js control the request for adding user info.
var express = require('express'),
router = express.Router(),
signup = require('../models/users/signup.js');
router.post('/signup', function(req, res) {
signup.addUser(req, res, function(err, data) {
if (err) {
res.json({ 'error': true, 'message': 'Error adding user .. !' });
} else {
res.json({ 'success': true, 'message': 'User added succesfully' });
}
});
});
module.exports = router;
Models Directory
Models are the files where you interact with your database. They contain all the methods and functions which will handle your data. This includes the methods for creating, reading, updating and deleting items.
var mysql = require("../db.js"),
mysqlPool = mysql.createPool(); // connects to Database
/**
* Defines Signup operations.
* @class
*/
var signup = function(){};
/**
* save user data
* @Function
* @param callback
* @param feedbackQuery
*/
signup.prototype.addUser = function(req, res, callback){
var nowDate = new Date().toISOString().slice(0, 19).replace('T', ' '),
params = [req.body.name, req.body.email, req.body.password,req.body.role, req.body.contact, req.body.gender, req.body.dob, req.body.address],
feedbackQuery = 'INSERT INTO users (name,email,password,role,contact,gender,dob,address) VALUES (?,?,?,?,?,?,?,?)';
mysqlPool.getConnection(function(err, connection){
connection.query(feedbackQuery, params, function(err, rows, fields) {
if(err){
connection.release();
callback(true, null);
}else{
connection.release();
callback(null, true);
}
});
});
}
module.exports = new signup();

