AppDividend
Latest Web Development Tutorials

Node js Express Tutorial For Beginners From Scratch 2018

941

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.

Related Posts
1 of 6
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.

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

Leave A Reply

Your email address will not be published.