AppDividend
Latest Code Tutorials

Node Express Example For Beginners 2020

18

Node Express Example For Beginners From Scratch 2020 is today’s leading topic. Express js is a minimal and flexible Node.js web application framework that provides a robust set of features to develop web and mobile applications.

We can build Web APIs through this framework very quickly, and it has tremendous support for the NoSQL databases like MongoDB. You can refer more about Node js Express js Framework on its Official Docs.

To work with this framework, I am assuming that you have installed Node.js on your machine.

Node Express Example

In this tutorial, we will study the Express framework. This framework is built in such a way that it acts as a minimal and flexible Node.js web application framework, providing a robust set of features for building single and multipage, and hybrid web applications.

First, we will install the Express Framework, and then we will start building a simple web application with the backend database of MongoDB.

What is Express.js?

Express.js is a Node js web application server framework, which is specifically designed for building single-page, multi-page, and hybrid web applications.

It has become the standard server framework for node.js. Express is the backend part of something known as the MEAN stack.

The MEAN is a free and open-source JavaScript software stack for building dynamic web sites and web applications which has the following components;

1) MongoDB – The standard NoSQL database

2) Express.js – The default web applications framework

3) Angular – The JavaScript MVC framework used for web applications

4) Node.js – Framework used for scalable server-side and networking applications.

The Express.js framework makes it very easy to develop an application that can be used to handle multiple types of requests like the GET, PUT, and POST and DELETE requests.

Step 1: Install Express Framework.

Go to the terminal and make one project folder and go in it.

$ mkdir expressdemo
$ cd expressdemo

Now Initialize the package.json file by the following command.

npm init

It will give us a series of questions and after that in your project folder, package.json file will be created.

Install express by the following command.

npm install express --save

Step 2: Create a server.js file in the root.

Create our Node.js server through the following code.

// server.js

const express = require('express');
const app = express();
const port = 3000;
app.listen(port, function(){
  console.log('Node js Express js Tutorial');
});

In our first line of code, we are using the require function to include the “express module.”

Before we can start using the express module, we need to make an object of it.

Here we are creating a callback function. This function will be called whenever anybody browses to the root of our web application which is http://localhost:3000.

The callback function will be used to send the string ‘Node js Express js Tutorial’ to the web page.

In the callback function, we are logging the string ‘Node js Express js Tutorial’ back to the client.

We are then using the listen to function to make our server application listen to client requests on port no 3000. You can specify any available port over here.

If we do not want to restart the server manually every time, then we can use a node package called nodemon. It resets the server every time we change the file.

npm install nodemon --save-dev

Change the package.json file and add the following line in the “scripts” object.

"scripts": {
    "start": "nodemon server.js"
},

When you type in terminal “npm start,” it will bootstrap the server, and when we change the files, it will automatically restart.

Step 3: Install the EJS templating engine.

If you do not know what is templating engine in Express then check out this  Template Engine in Express example.

To include the CSS and js files in the express, first, we will create a static directory called the public, and in that, we will put our CSS and JS files.

// server.js

app.use(express.static('public'));

Here we are going to use “ejs” as a templating engine, so first, we need to download that through NPM.

// server.js

npm install --save ejs

Now we need to update our server.js file to set the view engine.

// server.js

app.set('view engine', 'ejs');

We need to create one folder inside our root called views. In that folder make one file called index.ejs.

<!-- index.ejs -->

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>EJS Engine</title>
    <link rel="stylesheet" href="/css/bootstrap.min.css">
  </head>
  <body>
    <div class="container">
      <div class="jumbotron">
        Node js Express js Tutorial 2020
      </div>
    </div>
  </body>
</html>

To display this route, we just need to add the following code to the server.js file.

// server.js

app.get('/', function (req, res) {
   res.sendFile(path.join(__dirname,'public', 'index.html'));
});

Our index.html file inside the public folder looks like this.

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=He, initial-scale=1.0">
   <meta http-equiv="X-UA-Compatible" content="ie=edge">
   <title>Node js tutorial</title>
</head>
<body>
   Node js tutorial
</body>
</html>

Step 4: Configure Express Router.

Before we deep dive into routes, let’s understand the basics of routes in the Express web framework.

What are Routes

Routing determines the way in which an application responds to a client request to a particular endpoint.

For example, a client can make a GET, POST, PUT or DELETE http request for various URL such as the ones shown below;

http://localhost:3000/coins
http://localhost:3000/coins/post

In the above example,

  1. If a GET request is made for the first URL, then the response should ideally be a list of coins.
  2. If the POST request is made for the second URL, then we will save the data into the database.
  3. So based on the URL which is accessed, a different functionality on the web server will be invoked, and accordingly, the response will be sent to the client. This is the concept of routing.

Each route can have one or more handler functions, which are executed when the route is matched.

Set up the routes for our application. So use the Router module provided by Express js. First, create a folder inside root called routes. In that folder make one file called CoinRouter.js.

const express = require('express');
const app = express();
const CoinRouter = express.Router();

CoinRouter.route('/').get(function (req, res) {
  res.render('index');
});

module.exports = CoinRouter;

Now in the server.js filewe need to require the CoinRouter.js file.

// server.js

const CoinRouter = require('./routes/CoinRouter');

app.use('/coins', CoinRouter);

Switch to the browser URL: http://localhost:3000/coins/  It will display an index view.

The next step will be to create a bootstrap interface to add the coin name and coin price.

Step 5: Create a form.

In the views, the folder makes one file called create.ejs file.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>EJS Engine</title>
    <link rel="stylesheet" href="/css/bootstrap.min.css">
  </head>
  <body>
    <div class="container">
        <h1>Add Coin</h1>
        <form method="post" action="/coins/post">
          <div class="form-group">
            <label for="item">Coin Name</label>
            <input type="text" class="form-control" id="name" name="name">
          </div>
          <div class="form-group">
            <label for="item">Coin Price</label>
            <input type="text" class="form-control" id="price" name="price">
          </div>
          <button type="submit" class="btn btn-default">Submit Coin</button>
        </form>
    </div>
  </body>
</html>

The next step is to create a route in the CoinRouter.js file, so put the following code in it.

// CoinRouter.js

CoinRouter.route('/create').get(function (req, res) {
   res.render('create');
 });

Step 6: Install Mongoose Library.

We will use MongoDB for the database so set up a MongoDB database, so we need to download a package called Mongoose in our project.

npm install --save mongoose

Now, configure the database for our Node js application.

// server.js

const mongoose = require('mongoose');

mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/expressdemo');

Step 7: Install the body-parser module.

We are sending the form data to the Node js server, so we need to install the body-parser module to parse our posted data and insert that data into the MongoDB database.

npm install --save body-parser

Now, include this module in our server.js file.

// server.js

const bodyParser = require('body-parser');

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

Next is to create a model for our database. So create one folder in the root called models. In that folder, create one file called Coin.model.js

// Coin.model.js

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const Coin = new Schema({
  name: {
    type: String
  },
  price: {
     type: Number
  }
},{
    collection: 'coins'
});

module.exports = mongoose.model('Coin', Coin);

Now, create a  post route in the CoinRouter.js, put the following code in it.

// CoinRouter.js

const Coin = require('../models/Coin.model');

CoinRouter.route('/post').post(function (req, res) {
   const coin = new Coin(req.body);
   console.log(coin);
   coin.save()
     .then(coin => {
     res.redirect('/coins');
     })
     .catch(err => {
     res.status(400).send("unable to save to database");
     });
 });

Each route can have one or more handler functions, which are executed when the route is matched.

The general syntax for a route is shown below.

app.METHOD(PATH, HANDLER)

Wherein,

1) app is an instance of the express module

2) METHOD is an HTTP request method (GET, POST, PUT or DELETE)

3) PATH is a path on the server.

4) HANDLER is the function executed when the route is matched.

Our server.js file looks like this.

// server.js

const express = require('express');
const app = express();
const port = 3000;
const path = require('path');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');

mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/expressdemo');

const CoinRouter = require('./routes/CoinRouter');

app.use(express.static('public'));
app.set('view engine', 'ejs');

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

app.use('/coins', CoinRouter);

app.get('/', function (req, res) {
   res.sendFile(path.join(__dirname,'public', 'index.html'));
});

app.listen(port, function(){
  console.log('Node js Express js Tutorial at port', port);
});

Here we are defining a route if the URL http://localhost:3000/coins is selected in the browser. To the route, we are attaching a callback function which will be called when we browse to the coins listing URL.

When the URL contains /coins URI then it will execute CoinRouter which contains a whole lot of subroutes for Get, Post, Patch, and Delete requests.

Try to submit the Coin, and yes, it will successfully add to the MongoDB database.

Step 8: Display the coins list.

Now, we need to get the data from the database, so you just need to put the following code in the CoinRouter.js file.

// CoinRouter.js

CoinRouter.route('/').get(function (req, res) {
   Coin.find(function (err, coins){
      if(err){
        console.log(err);
      }
      else {
        res.render('index', {coins: coins});
      }
    });
});

Also, we need to modify that index.ejs view to show the data.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Node js Express Tutorial</title>
    <link rel="stylesheet" href="/css/bootstrap.min.css">
  </head>
  <body>
    <div class="container">
      <table class="table table-striped">
        <thead>
          <tr>
            <td><b>Coin Name</b></td>
            <td><b>Coin Price</b></td>
            <td colspan="2"><b>Action</b></td>
          </tr>
        </thead>
        <tbody>
          <% for(var i=0; i < coins.length; i++) { %>
          <tr>
            <td><%= coins[i].name %></td>
            <td><%= coins[i].price %></td>
            <td><a href="" class="btn btn-primary">Edit</a></td>
            <td><a href="" class="btn btn-danger">Delete</a></td>
          </tr>
          <% } %>
        </tbody>
      </table>
    </div>
  </body>
</html>

Step 9: Make edit view and route.

In the views folder, make one called edit.ejs. Also, we need to pass the data from the database by its id.

In MongoDB the primary key is _id. So we need to fetch the collection of data by its id. So write the following code into the CoinRouter.js file.

// CoinRouter.js

CoinRouter.route('/edit/:id').get(function (req, res) {
   const id = req.params.id;
   Coin.findById(id, function (err, coin){
       res.render('edit', {coin: coin});
   });
 });

Create an edit.ejs file in the views directory.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Edit Coin</title>
    <link rel="stylesheet" href="/css/bootstrap.min.css">
  </head>
  <body>
    <div class="container">
        <h1>Edit Coin</h1>
        <form method="post" action="/coins/update/<%= coin._id %>">
          <div class="form-group">
            <label for="item">Coin Name</label>
            <input type="text" class="form-control" id="name" name="name" value="<%= coin.name %>">
          </div>
          <div class="form-group">
            <label for="item">Coin Price</label>
            <input type="text" class="form-control" id="price" name="price" value="<%= coin.price %>">
          </div>
          <button type="submit" class="btn btn-default">Update</button>
        </form>
    </div>
  </body>
</html>

Now, code the update function to update the values in the database.

// CoinRouter.js

CoinRouter.route('/update/:id').post(function (req, res) {
   Coin.findById(req.params.id, function(err, coin) {
     if (!coin)
       return next(new Error('Could not load Document'));
     else {
       // do your updates here
       coin.name = req.body.name;
       coin.price = req.body.price;
 
       coin.save().then(coin => {
           res.redirect('/coins');
       })
       .catch(err => {
             res.status(400).send("unable to update the database");
       });
     }
   });
 });

So, now you can edit and update the data in the database.

Step 10: Delete the data.

Now, delete functionality is remaining, which we will do and then call it a day.

// CoinRouter.js

CoinRouter.route('/delete/:id').get(function (req, res) {
  Coin.findByIdAndRemove({_id: req.params.id},
       function(err, coin){
        if(err) res.json(err);
        else res.redirect('/coins');
    });
});

Our whole CoinRouter.js file looks like this.

// CoinRouter.js

const express = require('express');
const app = express();
const CoinRouter = express.Router();
const Coin = require('../models/Coin.model');

CoinRouter.route('/').get(function (req, res) {
   Coin.find(function (err, coins){
      if(err){
        console.log(err);
      }
      else {
        res.render('index', {coins: coins});
      }
    });
});

CoinRouter.route('/create').get(function (req, res) {
   res.render('create');
 });

 CoinRouter.route('/post').post(function (req, res) {
   const coin = new Coin(req.body);
   console.log(coin);
   coin.save()
     .then(coin => {
     res.redirect('/coins');
     })
     .catch(err => {
     res.status(400).send("unable to save to database");
     });
 });

CoinRouter.route('/edit/:id').get(function (req, res) {
   const id = req.params.id;
   Coin.findById(id, function (err, coin){
       res.render('edit', {coin: coin});
   });
 });

 CoinRouter.route('/update/:id').post(function (req, res) {
   Coin.findById(req.params.id, function(err, coin) {
     if (!coin)
       return next(new Error('Could not load Document'));
     else {
       // do your updates here
       coin.name = req.body.name;
       coin.price = req.body.price;
 
       coin.save().then(coin => {
           res.redirect('/coins');
       })
       .catch(err => {
             res.status(400).send("unable to update the database");
       });
     }
   });
 });

 CoinRouter.route('/delete/:id').get(function (req, res) {
   Coin.findByIdAndRemove({_id: req.params.id},
        function(err, coin){
         if(err) res.json(err);
         else res.redirect('/coins');
     });
 });

module.exports = CoinRouter;

Summary

  1. The express framework is the most common framework used for developing Node applications. The express framework is built on top of the node framework and helps in the fast-tracking development of server-based applications.
  2. Routes are used to divert users to different parts of the web applications based on the request made. The response for each route can be varied depending on what needs to be shown to the user.
  3. Templates can be used to inject content in an efficient manner. Jade is one of the most popular templating engines used in Node applications.

Finally, our Node js Express Tutorial For Beginners From Scratch 2020 is over. It’s the same code.

Related Posts

Node Express Image Upload

Setup Node Express in Docker

How to server static file in Express

AWS Lamda and Node Example

Node File System Example

Fork Me On Github

18 Comments
  1. fodasemeu nome says

    sinto muito, mas seu tutorial mereceria um pouco mais de carinho.
    faltou falar sobre o bootstrap e outras coisas que vc nem sequer menciona no tutorial.
    isso só demonstra falta de ensinar.

    1. Krunal says

      Obrigado por comentar. O Bootstrap não é o foco principal deste tutorial. O objetivo principal é o funcionamento com o node.js e o mongodb. Espero que você possa entender isso.

      1. fodasemeu nome says

        sim, só usei um exemplo de algo que não é explicado.
        como por exemplo: estou há 20 minutos no minimo tentando entender pq estou recebendo o erro:
        ReferenceError: /Users/user1/expresstut/views/index.ejs:19
        17|
        18|
        >> 19| <% for(var i=0; i
        21|
        22|

        coins is not defined

  2. fodasemeu nome says

    sendo que copiei e colei todos os codigos.
    não poderia estar dando isso. (estou preso no passo 8 por causa desse erro)

    o que estava me referindo no comentario passado era a falta de carinho em não explicar que estava ignorando a pasta css, ou para que servia o html inicial que estavamos colocando lá no inicio do tutorial.
    entende?

    em alguns pontos do tutorial, vc apenas falou: “coloque este codigo no arquivo X.” ok. mas qual a importancia deste codigo? o que ele faz? é um tutorial bom. porém para pessoas que estão começando (o foco deste tutorial) deixa ele um pouco vago.

    1. Krunal says

      Ok, da próxima vez eu tentarei o meu melhor para dar todas as explicações. Obrigado pela sugestão.

  3. fodasemeu nome says

    OH. i downloaded your git and SURPRISE!
    error.

    1. Krunal says

      what error?

    2. Krunal says

      What error you are getting??

      1. fodasemeu nome says

        simply not load the page.
        how i correct the error that showed up with my code?
        ReferenceError: /Users/user1/expresstut/views/index.ejs:19
        17|
        18|
        >> 19| <% for(var i=0; i
        21|
        22|

        coins is not defined

        1. Krunal says

          pass the coins variable to the view. It contains MongoDB data. If you have not added in the database, then please add coin first then go to the index page. Do not go directly.

        2. Krunal says

          I have forgotten to put the condition, but you need to first add the data.

          1. Justin says

            For other people who had this issue make the following change.

            This:
            res.render(‘index’);

            Should be:
            res.render(‘index’, {coins: coins});

  4. Klemen says

    Great tutorial! Quickest way to pick up the basics.
    There is one thing missing in example code: to make edit and delete button should be linked to their api routes.

  5. Will Long II says

    Great intro! Personally learn much faster with practical usage of new languages so this was extremely helpful as I have not delved into express much at all. While I took it as an exercise to be completed by the reader, think Klemen is right the href attributes should be linked to their respective routes for completeness I think. Jotted them down below if anyone needs them atm. Great Job Though! Thanks so much for taking time to create this.
    <a href="coins/edit/” for the edit button and
    <a href="coins/delete/” for the delete button.

    1. Will Long II says

      well so much for that it doesn’t like you using asp tags apparently lol. The ending after the last slash should be without the spaces between the opening and ending tags.

  6. Steven says

    Thanks, this page helped refresh my memory after not using node, express or mongoose for a while.

    I do have some feedback. I hope you find it useful.

    In step 3, when you add the route, you reference a ‘path’ variable and package which you have not yet instructed the user to load. (It’s shown, but not discussed, down in step 7). Running app at this stage results in an error.

    In step 3, you instruct the user to create an index.ejs template in /views, and an index.html in /public, but only instruct the user to to create the routes for the static file. Step 3 is named “Install EJS templating engine” but doesn’t actually exercise the templates at all.

    Your code samples repeatedly reference the boostrap css framework, and it’s in the github repo, but you make no mention of it. The use of bootstrap may be more meaninful if you include screen shots of the pages in the browser.

    Your CoinRouter.js file creates an ‘app’ constant, but doesn’t reference in the file.

    In Step 6, you instruct the user to install mongoose and use that package to connect a running mongodb instance on localhost, with just the instruction of “setup a MongoDB database”. For a “from scratch” article, it may be helpful to include more information about installing mongodb, or to link somewhere with more information. Perhaps https://docs.mongodb.com/manual/administration/install-community/

    In Step 8, your final ‘index.ejs’ file does not include the actual href url/value for the edit or delete links. They are included in the github repo.

    Your final ‘index.ejs’ could also include a link to the “create” form route.

    1. Krunal says

      Thanks man, I will try to follow my explanation with my code.

  7. Idan says

    I’m having problems uploading a coin – it wont reach post.

    the server shows me trying to upload the coin using /coin/create but non of the other views work.

    also I’m getting this error even after the suggested solution:
    ReferenceError: /Users/user1/expresstut/views/index.ejs:19
    17|
    18|
    >> 19| <% for(var i=0; i
    21|
    22|

    Any way to fix both of these problems?

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.