Geeks Trick
RestAPI for User Registration

User Registration RESTful API Using Node.js And Express 4


Check out the related post on Node Express App Structure.



Check how to connect MySql database using Node Express.



Build Up The Node App Structure

Following the node express folder architecture to build the RESTful API.

Directories

|___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
package.json

   {
  "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

app.js

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.

/controller/index.js

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.

/controller/users.js

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.

/models/users/signup.js

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();
Demo On Postman API app
RESTfulAPI-node-Express_mysql-user-Register-details
http:RESTfulAPI-node-Express_mysql-user-Register-Response-Message

Rehmaanali

Hi This Is Rehmaanali.
Blogging Is Just A Hobby.
Graduate In Bsc Computer Science

2 comments

  • While I do appreciate this tutorial, there is a lot of missing information. I don’t think you can assume people have looked at your other tutorials when you don’t explicitly say they should be completed first. They appear to be more of a suggestion to go check them out,

    Here are a few of the errors I encountered when trying to complete your tutorial:
    1. Missing from the package.json – “express-session”: “^1.15.2”, (possibly other packages missing from the package.json as well)
    2. Multiple pathing issues: e.g. “require(‘./users’)” but file name as “/controller/user.js”
    3. The script labeled “/models/user.js” is really “/models/users/signup.js”
    4. Express router errors due to “controllers/users.js” missing a “module.exports = router;” at the end of the file.

    Other than those issues thanks for posting!

    • Hi,
      Thanks for your effort for solving the errors in this article.
      I have made changes related to your list and add up a directory structure for better understanding the flow of the API.
      If you find any more bugs in this post please try to make me clear it out.
      Once Again Thanks.
      — Rehmaan Ali

Author

Rehmaanali

Hi This Is Rehmaanali.
Blogging Is Just A Hobby.
Graduate In Bsc Computer Science

Subscribe To Our Newsletter

Join our mailing list to receive the latest Articles news and updates from our team. 

You have Successfully Subscribed!