RESTful API Using Node.js and Express.js

RESTful API Using Node.js and Express.js

REST stands for REpresentational State Transfer. REST is a web standards-based architecture and uses HTTP Protocol. REST services address components as resources and are accessed by a common interface using HTTP standard methods. RESTful is the web service implementation of REST software architecture.

In this tutorial, I am going to explain how to build RESTful API using Node.js and Express.js using MongoDB as a database.

Prerequistics

I would request you all to install this software on your machine before proceeding ahead. I highly recommend installing Docker. If you install Docker, you would not need all of the software listed below.

  • Node.js version 12 and above.
  • MongoDB.
  • Postman or similar API testing software

Let me in the comments, if you face any issues with the installation.

Setting up project

Let’s set up a new Node project and create our RESTful API server.

Run this command in your terminal to create a new Node project.

mkdir restfuldemo && cd restfuldemo && npm init --y

Then, run this command to install the dependencies.

npm install --save express mongoose nconf uuidv4 body-parser

I will explain these node modules as we proceed further.

Open the project in your favorite editor. I recommend visual studio code.

Let’s code our project.

Building RESTful API Using Node.js and MongoDB

RESTful APIs are built around resources and you can perform operations on those resources using standard HTTP methods such as GET, POST, PUT, and DELETE. For our demonstration purpose, let’s take cars as an example resource and code a RESTful API server to perform operations on our resource.

RESTful API using Node and MongoDB

Let’s create a new file and name it config.json. This file will keep all of our configuration variables.

{
    "mongoURL": "mongodb://localhost:27017/restDemo",
    "port": 3005
}

Next, we are going to create an application file which is also an entry point of our system. Create a new file and name it app.js.

const express = require("express");
const nconf = require("nconf");
const bodyparser = require("body-parser");
const app = express();

app.use(bodyparser.json());

// load the config file
nconf
  .argv()
  .env()
  .file({
    file: __dirname + "/config.json",
  });

app.disable("etag");
app.disable("x-powered-by");
app.use("/api", require("./routes"));

app.listen(nconf.get("port") || 3000);
console.log("Server is running at", nconf.get("port") || 3000);

In the code shown above, we are loading the modules that we installed earlier. nconf is a configuration module and we are using it to access configuration variables across our application. Then, we are creating a new and registering on the /api endpoint.

Routers in the express.js framework are an inbuilt routing mechanism that helps us to create multiple HTTP endpoints and expose them to the front-end or browser.

Let’s create a new routes folder and create an index.js file in it. You can run this command to perform this operation or do it manually.

mkdir routes && cd routes && touch index.js

In index.js , add the following code.

const express = require("express");
const router = express.Router();

router.use('/cars', require('./cars'));

module.exports = router;

It’s always better to separate your codebase into multiple modules or files. Here in our case, we are using the index.js as an entry routes file that contains a list of all the other routes with specific endpoints. For our tutorial, we just have a /cars endpoint.

Let’s create the cars.js file inside the routes folder. Place the following code inside the cars.js.

const express = require("express");
const router = express.Router();
const models = require('../models/cars');

router.get('/', async (req, res) => {
    try {
        const carData = await models.getAllCars();
        return res.json({error: false, data: carData});  
    }
    catch(e) {
        res.status(500).json({error: true, data: []});        
    }
});

router.get('/:id', async (req, res) => {
    try {
        const carData = await models.getSpecificCar(req.params.id);        
        res.json({error: false, data: carData});
    }
    catch(e) {
        res.status(500).json({error: true, data: []});                
    }
});

router.post('/', async (req, res) => {
    try {
        const carData = await models.createNewCar(req.body);
        res.status(201).json({error: false, data: carData});
    }
    catch(e) {
        res.status(500).json({error: true, data: []});                
    }
});

router.put('/:id', async (req, res) => {
    try {        
        const carBody = req.body;
        carBody._id = req.params.id;
        const carData = await models.updateCar(carBody);
        res.status(201).json({error: false, data: carData});
    }
    catch(e) {
        res.status(500).json({error: true, data: []});                
    }
});

router.delete('/:id', async (req, res) => {
    try {
        const carData = await models.deleteCar(req.params.id);
        res.status(410).json({error: false, data: carData});        
    }
    catch(e) {
        res.status(500).json({error: true, data: []});                
    }
});

module.exports = router;

The code shown above defines the routes of the application. We can define various HTTP operations such as GET, POST, etc and we have defined them in each route.

Each route also calls the model function that handles the database-related operations such as adding an entry in the collections, fetching records from the collection, and so on.

Create a new folder naming models and inside the folder create a new file naming connection.js.

const mongoose = require("mongoose");
const schema = mongoose.Schema;
const nconf = require("nconf");

mongoose.connect(nconf.get("mongoURL"), {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

// validate MongoDB connection
const db = mongoose.connection;

// events

db.on("error", () => {
  console.log("MongoDB connection error");
  process.exit(0);
});

db.once("open", () => {
  console.log(
    'Connected to MongoDB Database engine'
  );
});

mongoose.set('useFindAndModify', false);

const carSchema = new schema({
    name: String,
    model: Date
});

module.exports = {
  carSchema: mongoose.model("cars", carSchema),
};

We are first making a connection to our MongoDB database. If the connection is successful, we are creating a new schema that defines how we want to store our records in the database.

Finally, we are exporting our schema so that we can use it in a different file.

Create a new file naming cars.js and place the following code in it.

const { carSchema } = require("./connection");

function getAllCars() {
    return new Promise(async (resolve, reject) => {
        try {
            let results = await carSchema.find({});
            resolve(results);
        }
        catch(e) {
            console.log(e)
            reject(e);
        }
    });
}

function getSpecificCar(carId) {
    return new Promise(async (resolve, reject) => {
        try {
            let results = await carSchema.findById(carId);
            resolve(results);
        }
        catch(e) {
            reject(e);          
        }
    });
}

function createNewCar(carData) {
    return new Promise(async (resolve, reject) => {
        try {
            let record = new carSchema(carData);
            let results = await record.save(carData);
            resolve(results);
        }
        catch(e) {
            console.log(e);
            reject(e);
        }
    });    
}

function updateCar(carData) {
    return new Promise(async (resolve, reject) => {
        try {
            let results = await carSchema.findOneAndUpdate({
                _id: carData._id
            }, carData, {
                new: true,
            });
            resolve(results);
        }
        catch(e) {
            reject(e);            
        }
    });
}

function deleteCar(carId) {
    return new Promise(async (resolve, reject) => {
        try {
            let results = await carSchema.findOneAndRemove({
                _id: carId
            });
            resolve(results);
        }
        catch(e) {
            reject(e);                        
        }
    });
}

module.exports = {
    getAllCars: getAllCars,
    getSpecificCar: getSpecificCar,
    createNewCar: createNewCar,
    updateCar: updateCar,
    deleteCar: deleteCar,
};

The code shown above contains multiple functions that help us to interact with the database. For example, the getAllCars() function returns all the cars present in the database collections while the getSpecificCar() function returns only the car you are looking for. The code is straightforward and simple, let me know in the comments if you have any doubts.

Let’s run the code and check out how it works.

Running the application

Run the code using the following command.

node app.js

You should see the following response in the terminal if everything is good.

Server is running at 3005
Connected to MongoDB Database engine

Now, let’s call the APIs and check the response.

First, call the GET API to get all the cars.

The URL would be localhost:3005/api/cars.

RESTful API using Node and Express

Let’s create a new car entry.

Change the HTTP type to POST and put the following JSON data.

Restful api using Node and Express

You can similarly call rest of the API’s and

Further Study:

Node.js MySQL Tutorial
Build a RESTful API using Node and MongoDB
HTML5 Push Notification System Using Nodejs MySQL Socket.io
Voice Controlled Drone Built Using Node and ARDrone

136 thoughts on “RESTful API Using Node.js and Express.js”

  1. Hi,

    Good tutorial for REST Api. Only one question remains, why are we calling this architecture as RESTFul Api and not RESTLess Api?

    Thanks

    Piyas

    1. Hi Piyas,
      We call it RESTful because it adheres the REST ( Representational state transfer ) principles which i have mentioned in second section. If web service do not fulfill it then its RESTless, so basically any web service which do not follows REST principles it is RESTless. Hope it clarify.

      Thanks,
      Shahid.

  2. You should put a disclaimer on this article telling readers that they should never, under normal circumstances, store passwords in clear text. Please update the article with more modern practices ensuring that passwords are hashed. Thanks!

  3. Those examples are not working, I’m geting error:
    TypeError: Cannot read property ‘handle’ of undefined.

    Seems that express.Router() return is not valid.

    1. Please download the code and run the npm install and make sure all packages correctly installed. Still dint work just shoot me an email. Code is perfectly working.
      Thanks.

      1. There are a lot of tutorials of the MEAN stack online. This was very useful to learn how to substitute MongoDB for MySQL even if it has vulnerabilities. Thanks a bunch! 🙂

  4. Great tutorial !I have a suggestion that why not have some explanations for your code. Not all of reader can fully understand your code. : )

  5. Great stuff Shahid,

    Maybe include and show use of MySql views or routines instead of inline mysql queries?

    Thank you very much!!

  6. great tutorial.i’m new with node express.
    is it phpmyadmin comes with node-sql package?

      1. i got some error at #1: POST /users
        after i post some values

        ReferenceError: mysql is not defined
        at Object.handle (C:Usersrazinah radziDesktopooREST.js:13:17)
        at next_layer (C:Usersrazinah radziDesktopoonode_modulesexpresslibrouterroute.js:103:13)
        at Route.dispatch (C:Usersrazinah radziDesktopoonode_modulesexpresslibrouterroute.js:107:5)
        at C:Usersrazinah radziDesktopoonode_modulesexpresslibrouterindex.js:195:24
        at Function.proto.process_params (C:Usersrazinah radziDesktopoonode_modulesexpresslibrouterindex.js:251:12)
        at next (C:Usersrazinah radziDesktopoonode_modulesexpresslibrouterindex.js:189:19)
        at next (C:Usersrazinah radziDesktopoonode_modulesexpresslibrouterindex.js:166:38)
        at Function.proto.handle (C:Usersrazinah radziDesktopoonode_modulesexpresslibrouterindex.js:234:5)
        at Layer.router (C:Usersrazinah radziDesktopoonode_modulesexpresslibrouterindex.js:23:12)
        at trim_prefix (C:Usersrazinah radziDesktopoonode_modulesexpresslibrouterindex.js:226:17)

  7. Thanks brother for this tutorial,

    I am new in javascript, do we have to use prototype ? or there is another easy way ?

    is there any angularjs implementation as a front end code for this tutorial ?
    Thanks, your help is appreciated.

  8. Pretty good tutorial, would have been a great tutorial if you explained
    each step so beginners could understand exactly what you are doing in the code, but it’s pretty simple to figure out anyways.

    Thanks

    1. Hey Tony,

      I thought to do this but then length becomes issue, no one likes and reads 3000 word post. I wanna keep it short and simple and damn useful.

      But i will consider your suggestion.

      Thanks.

  9. after about a min the api breaks down and i get this error code: “PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR”
    I restart it and it works for another min, then it breaks down again. Any help would be appreciated.

    1. Hi Khan,

      Please find code attached.

      connection.on(‘error’, function(err) {
      if(err.code === “PROTOCOL_CONNECTION_LOST”) {
      connection.destroy();
      }
      });

      1. Sorry, but I have the same problem and I cant fix it

        ‘{“code”:”PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR”,”fatal”:false}’

  10. Nice tut, but I would consider it like a first step, for beginers.
    Next step should be switching to mongoDB or any JS DB and entering in the MEAN world, so JS is used during the entire process chain 😉

  11. router.post(“/users”,function(req,res){
    var query = “INSERT INTO ??(??,??) VALUES (?,?)”;
    var table = [“user_login”,”user_email”,”user_password”,req.body.email,md5(req.body.password)];
    console.log(“mail: “+req.body.email);
    console.log(“pass: “+req.body.password);
    query = mysql.format(query,table);
    console.log(query);
    connection.query(query,function(err,rows){
    if(err) {
    res.json({“Error” : true, “Message” : “Error executing MySQL query”});
    } else {
    res.json({“Error” : false, “Message” : “User Added !”});
    }
    });
    });
    ************
    the response of this is :
    mail : undefined
    password : undefined
    INSERT INTO ‘user_login'(‘user_email’,’user_password’) VALUES (NULL , NULL)

    what is the problem with req.body.email and req.body.password? they don’t extract input data? what to do ??

  12. router.post(“/users”,function(req,res){
    var query = “INSERT INTO ??(??,??) VALUES (?,?)”;
    var table = [“user_login”,”user_email”,”user_password”,req.body.email,md5(req.body.password)];
    console.log(“mail: “+req.body);
    console.log(“pass: “+req.body.password);
    query = mysql.format(query,table);
    console.log(query);
    connection.query(query,function(err,rows){
    if(err) {
    res.json({“Error” : true, “Message” : “Error executing MySQL query”});
    } else {
    res.json({“Error” : false, “Message” : “User Added !”});
    }
    });
    });
    ***
    the result of POST request is :
    mail: undefined
    password : undefined
    INSERT INTO ‘user_login'(‘user_email’,’user_password’) VALUES (NULL,NULL)
    what’s wrong with req.body.email and req.body.password ? they don’t extract input data,what to do ?

  13. Hi,

    When I am inserting data through localhost:3000/api/users API. I am getting error.

    {
    “Error”: true,
    “Message”: “Error executing MySQL query”
    }

    All setting and table are correct.
    Please let me know the exact problem and also let me know could be debugged node.js program line by line ?.

  14. Hi,

    I am getting Error in localhost:3000/api/users API.

    {
    “Error”: true,
    “Message”: “Error executing MySQL query”
    }

    What is Exact problem ??
    Please guide me ??
    Also how would be able to debug code line by line??

  15. Rafael Antonio Lucio

    Hi, great article, but, how do you work with long URL?, ex: /api/users/:usersId/contacts/:contactId, I recommend you use Promises to queries on database, thanks!!

  16. Ole-Andreas Nylund

    Your tutorials are the best node.js tutorials I have come across on the web! Keep up the good work!

  17. Thanks for your tutorial.
    but can you help me, how to create and send result of json like this

    [
    [
    {
    “name” : “project_A”
    },
    {
    “data” : [
    {
    “price” : 50,
    “day” : 14,
    “month” : 0
    },
    {
    “price” : 150,
    “day” : 90,
    “month” : 3
    }
    ]
    }
    ],
    [
    {
    “name” : “project_B”
    },
    {
    “data” : [
    {
    “price” : 170,
    “day” : 33,
    “month” : 1
    },
    {
    “price” : 290,
    “day” : 60,
    “month” : 2
    }
    ]
    }
    ]
    ]

  18. Sasha Petrovich

    Hi Shahid,

    Awesome tutorial!!

    I came across this one thing that may be worth changing — currently REST gets created with one ‘connection’ from the pool. This one connection gets used and the pool actually never gets asked for another connection.

    I changed Server.js a little, to limit reduce of connections and explicitly ask pool to wait for free connection (mysql by default, limits number of connections to 100 on its end)
    REST.prototype.connectMysql = function() {
    var self = this;
    var pool = mysql.createPool({
    connectionLimit : 50,
    waitForConnection: true,
    host : ”,
    user : ”,
    password : ”,
    database : ”,
    debug : false
    });
    self.configureExpress(pool);
    }

    in REST.prototype.configureExpress we pass in ‘pool’ instead of passing ‘connection’.

    Over in REST.js we wrap each connection.query into pool.getConnection (pretty much as per your guide on mysql and pools)

    Cheers,
    Sasha

    1. Good Suggestion.
      It is important thing for losting connection issue.
      Thanks Sasha Perovich.

  19. I tried to install this and get the following error when I run the app:

    ReferenceError: mysql is not defined
    at C:xampphtdocsnodejsnode_modulesREST.js:27:17
    at Layer.handle [as handle_request] (C:xampphtdocsnodejsnode_modulesexpresslibrouterlayer.js:95:5)
    at next (C:xampphtdocsnodejsnode_modulesexpresslibrouterroute.js:131:13)
    at Route.dispatch (C:xampphtdocsnodejsnode_modulesexpresslibrouterroute.js:112:3)
    at Layer.handle [as handle_request] (C:xampphtdocsnodejsnode_modulesexpresslibrouterlayer.js:95:5)
    at C:xampphtdocsnodejsnode_modulesexpresslibrouterindex.js:277:22
    at Function.process_params (C:xampphtdocsnodejsnode_modulesexpresslibrouterindex.js:330:12)
    at next (C:xampphtdocsnodejsnode_modulesexpresslibrouterindex.js:271:10)
    at Function.handle (C:xampphtdocsnodejsnode_modulesexpresslibrouterindex.js:176:3)
    at router (C:xampphtdocsnodejsnode_modulesexpresslibrouterindex.js:46:12)

    DB is installed and when i type npm start it starts up as defined.

    not sure what I am doing wrong.

    any help is appreciated

  20. It would be nice to see how to change this so that each route is handled by a seperate controller in its own file.

  21. Great tutorial! can you do something similar with MongoDB instead of MySQL? Thanks!

  22. Love the tutorial but I have a question revolving around the use of the pool connection instead of the normal connect function of the MySQL library. When I was reading the GitHub documentation about the library, I noticed they said you should use the release() function at the end of every function to allow the connection to return back to the pool. I did not notice this in your examples. Can you explain why?

      1. Hello Shahid,
        I have tried adding release() at the end of all APIs, but on second hit of API it throws error “Error: Connection already released”. Can you please explain why this error is occurring on second time, how we fix this.
        Thanks

        1. I got the answer from Sasha Petrovich’s comment, this was exactly my problem. And Yes, solution was also from your article “Nodejs and MYSQL” only. Thanks

  23. Hey Mate,

    Sweet tutorial. It helped me take a makeshift api using php into a RESTful API and it only took an hour and a half. Next steps for my own API is that it requires authentication. It would be cool to have a tutorial on this.

  24. I already viewed your AngularJS Single page application blog. How can get Node’s Restful api response from that AngularJS Application. I have already tried $http call in Angular that is not working. Please provide how to handle this Restful Api response in AngularJS Single page application or how can I render Restful api response in express framework…..!

      1. It works fine…… But i have an another problem. Firefox tell (CROSS DOMAIN ISSUE).

        Because my AngularJS Single page App runs on port 3000 (localhost:3000) and my API runs on 8000 (localhost:8000). that’s y the issue came.

        I also used some .htaccess file, but nothing happened. One good thing is Chrome has a (plugin for disable CROSS DOMAIN ISSUE), In that it works.. I was totally confused.

        Finally, my objective is creating Single page AngularJS web app using node restAPI with same project folder. ie( project running path like “localhost:3000/” means my API calls running at “localhost:3000/api/”)……..That all…! Help me folk….! I believe i’m in expert hand…!

        1. Since you are in same port try calling /api/ from angular service and if its still give cross domain origin add the following code in server file.

          app.use(function(req, res, next) {
            res.header("Access-Control-Allow-Origin", "*");
            res.header("Access-Control-Allow-Headers", "X-Requested-With");
            next();
           });
          1. Nothing…! Happened….! Can i send my files to your mail…! I think I’m going to maintain a wrong folder structure. Once you found that, give a guidance to maintain perfect folder structure……! Thank you Shahid……!

  25. Scott Engemann

    Nice tutorial. Alternatively you can send a status with the response:

    res.status(200/404/500….).json(responseData);

  26. nice tutorial and worked fine mr. Shahid Shaikh, please teach we about your this tutorial to auth some API.

  27. When I try and install I get the following – is that correct

    npm WARN package.json RESTful-API@0.0.1 No description
    npm WARN package.json RESTful-API@0.0.1 No repository field.
    npm WARN package.json RESTful-API@0.0.1 No README data

    And when I run the app I get…

    Cannot GET /

    Can’t get much more than that…

    Any ideas.

  28. AM!

    Running the insert code I noticed:

    When the query string is like:

    var query = “INSERT INTO ??(??,??) VALUES (?,?)”;

    I got an error and in MySQL debug mode it logged:

    message: ‘Column count doesn\’t match value count at row 1’ }

    changing it to this:

    var query = “INSERT INTO ??(??,??) VALUES (?)”;

    it worked, but the password is not in MD5. When I console.log md5(req.body.password) – I receive undefined as the response.

    Thanks

    Any ideas?

  29. Correction MD5 does work – when I do console.log(md5(“xyz”)); it seems to MD5 in console log…

  30. Got it working now, my mistake was, that I had built a HTML form and 2 elements had the same name, therefore passing 2 elements into the field email, which in turn got pulled into the sql param query.

    Thanks

  31. Charles Heizer

    Great tutorial, I learned a lot from this. I would love to see an addition to this by incorporating swagger api doc. Do you have any plans to do this?

  32. Charles Heizer

    Great tutorial, I learned a lot. Any chance you will extent the tutorial to include Swagger support for documenting the API?

    Thanks!

    PS: I tried posting this once before but it never showed up 😉

    1. Shahid (UnixRoot) Shaikh

      Yeah will look into swagger.

      Reason why it didn’t show up is comment moderation.

  33. Hi Shahid,

    It is a very good tutorial. I got all of the things very easily. I have a doubt for put statement. When we are updating any user details then it is also updating the password coressponding to invalid email.
    So how can we fix it. We need to write the code to restrict it or is there any predefined function for the same.

    Please help me.

    Thanks & Regards,
    Shravan Jain

  34. Very good tutorial for Nodejs beginner like me to follow and study.

    I’ve something that confuse me when I follow down to get user by userId.
    router.get(“/users/:userId”,function(req,res){
    ……………..
    });

    What if i want to have another function that can get user by user’s email addres?
    It definitely cannot use router.get(“/users/:email”,function(req,res) to do it.

    How can I have get user function with user_id and email options?

    1. Shahid (UnixRoot) Shaikh

      If you want that in URL then you can either go with /:id/:email or having /:email in separate function would work with same URL.

  35. Fabulous tutorial for NodeJS beginners,

    But I have one simple doubt.

    How can I call function in rest function.

    eg. function demo(connection)
    {
    connection.query(“select * from user_login where user_id = 1”, function(err, rows){
    return rows;
    });
    }

    router.get(“/users”,function(req,res){
    var query = “SELECT * FROM ??”;
    var table = [“user_login”];
    query = mysql.format(query,table);

    console.log(demo(connection));

    connection.query(query,function(err,rows){
    if(err) {
    res.json({“Error” : true, “Message” : “Error executing MySQL query”});
    } else {
    res.json({“Error” : false, “Message” : “Success”, “Users” : rows});
    }
    });
    });

    But demo doesn’t returns the rows.

    1. Shahid (UnixRoot) Shaikh

      It’s because demo is synchronous and connection.query() is asynchronous function.

      Learn more about Async handling here.

      1. I read that blog thoroughly. But even I doesn’t know about how can I achieve my solution.

        My requirement is whenever each and every api call that will check that should be called from valid users.

        So that I need to call a function (eg.function validate()) that may be return 0 or 1.

        Help me Shahid. I believe I’m in expert hand.

        1. Shahid (UnixRoot) Shaikh

          All you need is to write a middleware and include it in before every route.

          Please refer this tutorial to develop it.

  36. Thanks for yuor question.

    I will make some shopping mall site by using Node JS.

    One question in this turtorial is
    – you use a tool to send verb to your node js to handle CRUD right?
    – what about implemeneting CRUD in industry? I meant I tried to delete a selected row with route.delete() in database sent from a HTML view (method=’delete’). Seemingly It did not work. From my perspective, it should be worked. If view sends a method with delete to controller with route.delete() like you made here.

  37. Hey Shadhid,

    Awesome API, I’m new to node and express can you please tell me how can i query the database with promise, I’m using angular datatables and i need promise in my backend api.

    Thanks
    Wcan

  38. yeah I’ve read this tutorial its good and very help full, what i don’t can’t understand is how can i use var Promise = require(‘bluebird’);
    OR
    var async = require(‘async’);

    with the following code

    router.get(‘/HouseList/:TableName’, function(req, res)
    {
    var table_name = [req.params.TableName];

    var query = “SELECT * FROM house”;

    query = mysql.format(query, table_name);
    connection.query(query, function(err, rows)
    {
    if(err)
    {
    res.json({“Error” : true, “Message” : err.toString()});
    }
    else
    {
    res.json({“Error” : false, “Message” : “Success”, [req.params.TableName] : rows});
    }
    });
    });

    anything i try it give me an error. Thanks in advance

  39. POST method only works for x-www-form-urlencoded header. how can i achieve POST using plain header (body – json).?

      1. Awesome Man. I already written it. After comment

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

        it works fine.

  40. Hey ,

    i have a question….here it is ..

    i am using logger.js and logging.js in my project i need to replace the logging.js with logger.js

    with out any confliction’s ..this is my concern

    Note:
    i am using my internal framework to build the project. reply me asap.

  41. Thanks for sharing your knowledge. How to implement multi tenant architecture with seperate database for each tenant?

  42. Fernandes Guimarães

    Hello Shahid. Nice tutorial, thx for it.
    I have a little issue, perhaps you can help me. I’m trying to print the result in an HTML table, but all I get is [object Object] printed in by table.

    I’m using this script in the HTML file:

    $.getJSON(“/api/clients” , function(req) {
    var tbl_body = document.createElement(“tbody”);
    $.each(req, function(row) {
    var tbl_row = tbl_body.insertRow();
    $.each(this, function(k , v) {
    var cell = tbl_row.insertCell();
    cell.append(document.createTextNode(v.toString()));
    })
    })
    $(“#cl-db”).append(tbl_body);
    console.log(tbl_body);
    });

    Any clues on how to proceed? I’m new to all of this.

    Ps: I changed ‘users’ for ‘ clients’ in my routes.

    1. Shahid (UnixRoot) Shaikh

      Try JSON.parse(JSON.stringify(variable-which-prints-object-object))

  43. Hi Shahid,

    This Tutorial is very useful. Thanks for it.
    Actually now I am working on Authentication based web and mobile apps using MongoDB, express.js and node.js., In that I am stuck in how to get the api call after verify the username and password. Actually we are using some JWT token generating authentication method. The user information table which contains user details are separate collections in MongoDB and the data which is used to create the api is another collections. The process is, while login the application it verifies the username and password combination and after that it will call the api which contains the corresponding user data. Here the collection is different so we are unable to get the api response after successful login user. Can any one please help me.

    Thanks
    Vicky

    1. Shahid (UnixRoot) Shaikh

      Hi,

      Thanks for explaining the issue.

      To solve it, you need a middleware hooked before your API calls which in turns checks whether a token is correct or not.

      I actually wrote the complete tutorial on JWT using RethinkDB. You can replace RethinkDB model code with MongoDB and I am sure it will work like charm.

      Here it is.

  44. Hi Shahid,
    thanks a lot for this tutorial.
    I am very new to node and express and it is very well explained so we got it up and runnung.
    We are running the webclient(NGINX), the API(Node & Express) and the MySQL in different Docker containers which works well together.
    Just one question, how can i do a proper call to the API – lets say get all users with this function of your REST.js:

    router.get(“/users”,function(req,res){
    var query = “SELECT * FROM ??”;
    var table = [“user_login”];
    query = mysql.format(query,table);
    connection.query(query,function(err,rows){
    if(err) {
    res.json({“Error” : true, “Message” : “Error executing MySQL query”});
    } else {
    res.json({“Error” : false, “Message” : “Success”, “Users” : rows});
    }
    });
    });

    from a js.-file included in the index.html at the webfrontend?
    And, of course get the right result error/success back.

    Many thanks for your time,
    Joe

      1. Hi Shahid,
        thanks for your anser. Found out that out already 😉

        Can you maybe give a small example of how to call a stored prodessure with 2 input parameters and the restult returned.
        That wouls made my day.

        Many thanks for your sepended time in advance,
        Joe.

  45. Hello i have a problem i’ve replace the credential by mine with remote MySQL DB (host, database, name, password) and i have this error “ISSUE WITH MYSQL nError: getaddrinfo ENOTFOUND MY_DATABASE_ADDR MY_DATABASE_ADDR:3306” Dont know how to fix it ?

      1. But the database is already created i can access it via phpmyadmin and i tried with another db i used for another project still have the same issue

  46. Hi! My app only works with x-www-form-urlencoded header.
    I have tried commenting out app.use(bodyParser.urlencoded({ extended: true }));
    But still not working with form-data

    1. Keep getting this error;

      Error: Illegal argument undefined
      at module.exports (C:\Program Files\nodejs\login_register_app\node_modules\md5\md5.js:152:13)
      at C:\Program Files\nodejs\login_register_app\REST.js:15:79
      at Layer.handle [as handle_request] (C:\Program Files\nodejs\login_register_app\node_modules\express\lib\router\layer.js:95:5)
      at next (C:\Program Files\nodejs\login_register_app\node_modules\express\lib\router\route.js:131:13)
      at Route.dispatch (C:\Program Files\nodejs\login_register_app\node_modules\express\lib\router\route.js:112:3)
      at Layer.handle [as handle_request] (C:\Program Files\nodejs\login_register_app\node_modules\express\lib\router\layer.js:95:5)
      at C:\Program Files\nodejs\login_register_app\node_modules\express\lib\router\index.js:277:22
      at Function.process_params (C:\Program Files\nodejs\login_register_app\node_modules\express\lib\router\index.js:330:12)
      at next (C:\Program Files\nodejs\login_register_app\node_modules\express\lib\router\index.js:271:10)
      at Function.handle (C:\Program Files\nodejs\login_register_app\node_modules\express\lib\router\index.js:176:3)

  47. Hi, I would like to see a version with express-validator. Does prototype approach change the way this validation is implemented?
    Thanks!!!

  48. Hi
    I am new to creating a rest api through express js and try to creating one through your this blog. but i am not able to post data through postman. Its always showing Cannot POST /api/users/ Any suggestion?

  49. its working. the node_module folder in downloaded code was might be buggy. freshly installing npm gets working.

  50. The code works fine till i get it to print hello world or something. But as soon as i start hitting the database to insert or fetch records it starts giving me errors in the console.The “npm start” command doesn’t works once i start hitting database. Why am i getting the error.

  51. Hi Nice Tutorial

    But my problem is MySQL user authentication, with this example, can you please explain me.

  52. I want to execute two insert queries in Post method. But by default only the first query gets executed ignoring the second. Below is the code I tried:
    router.post(“/promoinsert/:PriceAfter/:PromoID/:description/:StartDate/:EndDate”,function(req,res){
    var query = “INSERT INTO ??(??,??,??,??,??,??) select ??,??,??-??,??-??,case when ??-?? var table = ["tb_promo_item","model_name","sku","new_acc_amt","upg_amt","port_in_amt","AAL_amt",
    "model_name","sku","SOR_price","standard_IR","SOR_price","standard_IR","SOR_price","standard_IR",req.params.PriceAfter,"SOR_price","standard_IR",req.params.PriceAfter,"SOR_price","standard_IR",req.params.PriceAfter,"SOR_price","standard_IR",req.params.PriceAfter,"tb_item"];["tb_promotion","promotion_id","description"
    ,"start_date","end_date",req.params.PromoID,req.params.description,req.params.StartDate,req.params.EndDate];
    query = mysql.format(query,table);
    connection.query(query,function(err,rows){
    if(err) {
    res.json({"Message" : "Error executing MySQL query"});
    } else {
    res.json({"Message" : "Records inserted"});
    }
    });
    });

  53. Hello,
    Its great tutorial and i want to use socket.io in REST.js file how can i access this in REST.js. Its difficult to use socket variable in external file. Awaiting for your reply. Thanks in advance.

  54. Hi, thank for this tutorial. It is greatfull!
    however i have got an error when i try to POST and get th param with “req.body.name…”

    for this issue i have add bodyParser in server.js after have do a npm install of that:

    var bodyParser = require(‘body-parser’);
    app.use(bodyParser.json()); // support json encoded bodies
    app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies

    And i haven’t got an error after. it work fine!
    Thanks!

  55. sir… great article and my api working funtastic.
    but my code run on json(applicaton/json)
    not show on above x-www-form-urluncoded.
    plz explain it.

  56. Hi that tutorial was great , but how do you authenticate since using sessions in APIs is quite impossible for devices like Android APPS? In the way I see Google API Keys work

  57. Hi,

    getting this error,

    can someone help me here ?


    ISSUE WITH MYSQL
    Error: connect ECONNREFUSED 127.0.0.1:3306
    npm ERR! code ELIFECYCLE
    npm ERR! errno 1
    —-

  58. Sanjeev Vishwakarma

    Great tutorial for Rest services,
    I’m facing some issues while calling microservices using node and express from angular component , can any one brief me about file structure and router in node. i am able to call microservice from server.js but unable to do it by angular component . Please help me

Comments are closed.