AppDividend
Latest Code Tutorials

Node js Express Tutorial For Beginners From Scratch 2018

3,423

Node js Express Tutorial For Beginners From Scratch 2018 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 js Express Tutorial

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

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');
});

If we do not want to restart the server manually every time, then we can use 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 “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 EJS templating engine.

For include the css and js files in the express, first, we will create a static directory called 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 2018
      </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 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.

Set up the routes for our application. So use 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 index view.

Related Posts
1 of 10

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, 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>

Next step is to register 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 setup 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 body parser module.

We are sending the form data to the Node js server, so we need to install 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");
     });
 });

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);
});

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 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 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;

Finally, our Node js Express Tutorial For Beginners From Scratch 2018 is over. I have uploaded the code on Github.

Fork Me On Github

16 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.

  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.

Leave A Reply

Your email address will not be published.