top
April flash sale

Search

Node JS Tutorial

Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. Go to ‘https://expressjs.com/’ and explore for more information to know about express. This site has some links to API, express-generator, Guide with some examples. We will be going to cover some of the topics, which will help you to build a better application using express. Also in express.js site, there are advanced topics like template engines, process managers, security and performance with some best practices. Finally, resources are a great place to known and ask for questions. Let us start with the course which will cover some of the topics like routes, template engine, middleware, body parsing, cookies, authentication etc. This would be good enough to build an express application.  Brand new express application from scratch: Install express using npm install express –g for globally for the terminal.  Open your IDE which has terminally inbuilt in it like visual studio code. Create a folder express-app which will have all the examples we are going to work on. Type ‘npm init’ in terminal to generator the package.json which will prompt a few things like version, description and so on. For now, we can continue with default ones. If you switch to explorer, package.json is generated and open it to see the values are generated. Now let's install few dependency i.e. npm install –save express nodemon (to watch and refresh server without restarting it) Since we will code in ES6 syntax, we need to install compilers for conversation. npm install –save-dev babel-cli babel-preset-evn babel-stage-0 Check the dependencies and dev-dependencies in package.json to make sure they are installed and segregated accordingly. Now we want to change the scripts section to add a start which will be used to start our server. “start” : nodemon ./index.js –exec babel-node –e js  Add babel configuration inside a new file .babelrc as shown below to run our ES6 code to compatible code in server { “presets”: [“env”, “stage-0”] } Finally, we need to create an index.js file which we used in start script of package.json. We can name it differently but the same should be used in package.json. Section 1:[index.js] Import express from ‘express’;  const app = express();  const port = 3000;  app.listen(PORT, () => {  console.log(`Server is running on port ${PORT}`);  }); Run npm start in the terminal and observe that server is running. Note: To get mock data in json, we can use https://www.mockaroo.com/ which we are going to serve from the server. Section 2: Let's extend the express app to add data to the server. Create a new folder ‘data’ and create a data.json with around 25 records of mock data. In Index.js file, import this data import data from './data/data.json' Under the console.log in the callback of app.listen, lets console.log this data. console.log(data); If you haven’t stopped the server, you will see the data in the console.log as nodemon is refreshing it on saving.  If you run localhost:3000, you will see that data is not sent to the front end, they are still in server. Section 3:  Creating a route, which is responsible for getting your page or data requested from the server. There are basically four methods  GET, POST, DELETE and PUT. It follows a request-response paradigm. When we type in localhost:3000 in a browser, we see ‘Cannot Get /’ displayed because the default route is Get command. Lets add the route for ‘/’. app.get('/', (req, res) =>      // get data first      res.send(`get request called on PORT: ${PORT}`);  ); Test in a browser and observe that a response has been displayed in the browser. Similarly we can do same for other methods i.e POST, PUT and DELETE. app.post('/newItem', (req, res) =>      // get data first      res.send(`post request called on PORT: ${PORT}`);  );  app.put('/item', (req, res) =>      // get data first      res.send(`put request called on PORT: ${PORT}`);  );  app.delete('/item', (req, res) =>      // get data first      res.send(`delete request called on PORT: ${PORT}`);  ); We can test this method using POSTMAN. (www.getpostman.com) Select POST method and type localhost:3000/newItem -> Click Send Select PUT method and type localhost:3000/item -> Click Send Select DELETE method and type localhost:3000/item -> Click Send Note: We can insert body via POST Man and another cool feature of the postman is ‘code’ option.  We get the API calling in our preferred language. Section 4: Now instead of sending a simple text, let us send some data actually. Replace the string with data we had from data.json file. Normally, we make a DB call and return the response. app.get('/', (req, res) =>      // get data first      res.json(data)  ); Test the same in a post and observe that data is displayed. The same thing can be viewed from the browser as well.  So basically, we can use any of the front modules like react to build a useful view. Section 5: Some times, we need to serve some static files like CSS, HTML, images etc. Create a new folder ‘Images’ and copy the images from your pictures folder [for windows - Libraries\Pictures]. Here we are going to use express.static inbuilt method to add a static path to the server. app.use(express.static('public'));  For now, think that ‘use’ is a method that allows adding specific middleware. ‘Use’ method basically takes the first argument as the route and if it is not provided then it would correspond to the default route ‘/’. Check and add some files to a public folder, for now, an image. Now switch to the browser and enter localhost:3000/[file name in public folder]. The browser should display that image. Similarly we can provide images as static And app.use('/images', express.static('images')); Now browser to localhost:3000/images/[imageName] and should display that image. Complete code till this point: importexpressfrom'express';  importdatafrom'./data/data.json';  constapp = express();  constPORT = 3000;  // This is for the public folder on path /  app.use(express.static('public'));  // this is for images folder on path images  app.use('/images', express.static('images'));  app.get('/', (req, res) =>  // get data first  res.json(data)  );  app.post('/newItem', (req, res) =>  res.send(`post request called on PORT: ${PORT}`);  );  app.put('/item', (req, res) =>  res.send(`put request called on PORT: ${PORT}`);  );  app.delete('/item', (req, res) =>  res.send(`delete request called on PORT: ${PORT}`);  );  app.listen(PORT, () => {  console.log(`Server is running on port ${PORT}`);  console.log(data);  }); Section 6: Route parameters Till now, we played around with routes without parameters. Now we will extend this example to consider routing parameters. Try to get an item by id from the mock data, for which we need to provide a route with path item and id as parameter. app.get('/item/:id', (req, res, next) => {      // extract the parameters and all parameter are converted to string      console.log(req.params.id);     // Conversation to number      let user = Number(req.params.id);      console.log(user);      // retrieve the specific user based on id from out mockData.      console.log(data[user]);      res.send(data[user]);  }); Now test by entering localhost:3000/item/04 and see that corresponding data is retrieved by comparing with the data in data.JSON file. The same thing can be observed in the terminal because of the console.log. We can also send multiple parameters like say we want to categorize the item further like ‘item/:category/:id’. Route Handlers: We have been using Route handler all this time without knowing it. The code gets called inside the callback is called route handler. app.put('/item', (req, res) =>      res.send(`put request called on PORT: ${PORT}`); ); Imagine if you want to handle multiple route handlers in a single route. For this, in express, we have something called next which is 3rd argument used above. For the same route of ‘item/:id’, lets add another handler. app.get('/item/:id', (req, res, next) => {      … //previous code      next();  }, (req, res) => {       console.log(‘Data is returned’);  }); ‘next’ should always be called when we work using middleware otherwise the request is not processed further. Navigate to the same URL to get the specific item and observe data is displayed in the browser. Also, look into the terminal to see data is returned to acknowledge that an extended route handler is called. app.get('/item/:id', (req, res, next) => {  console.log(req.params.id);  letuser = Number(req.params.id);  console.log(user);  console.log(data[user]);  res.send(data[user]);  next();  }, (req, res) =>  console.log('Did you get the right data?')  ); We have a few common methods on the response object which we need to understand before using them. For example, till this point we used res.send and res.json to return the data from the server. It is important to understand the difference.  Send method is for sending the response and has the intelligence to set the content-type based on the content sent. For example, is body is a buffer the content type is application/octet-stream. But if that is so then why do we need res.json.  JSON method internally uses the send method but does some formatting based on options like replacers and spaces before calling the send method so that the client can directly consume it. There is another res.end method which as names suggest it ends the session. It is useful if we don’t have any data but just to set status and end. For data cases, we can rely on send and JSON method which will end as well.  We have res.redirect to redirect our page to new page like res.redirect(‘www.nodejs.org’); For downloading the files from servers, we can use res.download. This is very similar to res.sendFile which allows does the same. For other methods refer to response methods here: http://expressjs.com/en/guide/routing.html Sometimes we need to have different methods for the same route like app.get(‘/item’), app.put(‘/item’) and app.delete(‘/item’). We can chain all of this together as shown below: app.route('/item')      .get((req, res) => {          res.send(`a get request with /item route on port ${PORT}`)      })      .put((req, res) =>          res.send(`a put request with /item route on port ${PORT}`)      )      .delete((req, res) =>          res.send(`a delete request with /item route on port ${PORT}`)  ); We are using the app.route method to create chainable route handlers for a route path. Template engines: Express provides support to a lot of template engines ‘out-of-box’. We can refer to them here - https://expressjs.com/en/resources/template-engines.html Out of this, some of the most popular are Pug, hbs, ejs. Let’s compare hbs and pugs. Hbs – syntax is similar to html template just that variables are in double curly braces.<div class=’entry’>  <h 1>{{title}}</h 1>  </div>  Pub (jade) – is kind of new syntax and uses white space for differentiation. It is lot smaller.  .entry  h1=title Let us take any of the above examples and implement templates. First we need to set the ‘view engine’ with our interested template engine say pub. const express = require('express');  const path = require('path');  const app = express();  app.set(‘view engine’, ‘pug’); Now express will take care rest but we need to say where it has to look for templates. Create a new folder called ‘views’ and set it as views to look for.  app.set(‘views’, path.join(__dirname, ‘./views’)); Since we have given folder path, express assumes that index file exists and loads it accordingly. Let us create an index.pug file and add some basic html content. doctype html  html      head      body          h1 Index Page          p This is the index page Now the route has to know that it has to render this page accordingly. app.get(‘/’, (req, res, next) => {  return res.render(‘index’);  }); Start the server and observe that the template is rendered correctly. Now, look into the HTML generated using developer tools, which is optimized by removing white spaces. If we want to generate the html in a readable format, we can enable a flag for development environment only. app.locals.pretty = true; res.locals is an object where we can add new fields in specific route and use them in the *.pug file. To illustrate this, let’s use a middleware to listen to error. app.use((err, req, res, next) => {  res.locals.message = err.message;      const status = err.status || 500;      res.locals.status = status;  res.locals.error = err;      res.status(status);      return res.render('error');  }); Update the *.pug file to display error message if error occurs.  [we can convert an existing error page to pug format through some of the online converters] doctype html  html      head      body          h1 Index Page          p This is the index page          if (error)  h1.mr-3.pr-3.align-top.border-right.inline-block.align-content-center=status        .inline-block.align-middle          h2#desc.font-weight-normal.lead=message          pre=error.stack constexpress = require('express');  constcreateError = require('http-errors');  constpath = require('path');  constapp = express();  app.set('view engine', 'pug');  app.locals.pretty = true;  app.set('views', path.join(__dirname, './views'));  app.get('/', (req, res, next) => {  returnres.render('index');      });  app.use((req, res, next) => {  returnnext(createError(404, 'File not found'));  });  app.use((err, req, res, next) => {  res.locals.message = err.message;  conststatus = err.status || 500;  res.locals.status = status;  res.locals.error = req.app.get('env') === 'development' ? err : {};  res.status(status);  returnres.render('error');  });  app.listen(3000);
logo

Node JS Tutorial

Implementing Express

Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. 

Go to ‘https://expressjs.com/’ and explore for more information to know about express. This site has some links to API, express-generator, Guide with some examples. We will be going to cover some of the topics, which will help you to build a better application using express. Also in express.js site, there are advanced topics like template engines, process managers, security and performance with some best practices. Finally, resources are a great place to known and ask for questions. 

Let us start with the course which will cover some of the topics like routes, template engine, middleware, body parsing, cookies, authentication etc. This would be good enough to build an express application.  

Brand new express application from scratch: 

Install express using npm install express –g for globally for the terminal.  

Open your IDE which has terminally inbuilt in it like visual studio code. Create a folder express-app which will have all the examples we are going to work on. 

Type ‘npm init’ in terminal to generator the package.json which will prompt a few things like version, description and so on. For now, we can continue with default ones. 

If you switch to explorer, package.json is generated and open it to see the values are generated. 

Now let's install few dependency i.e. npm install –save express nodemon (to watch and refresh server without restarting it) 

Since we will code in ES6 syntax, we need to install compilers for conversation. 

npm install –save-dev babel-cli babel-preset-evn babel-stage-0 

Check the dependencies and dev-dependencies in package.json to make sure they are installed and segregated accordingly. 

Now we want to change the scripts section to add a start which will be used to start our server. 

“start” : nodemon ./index.js –exec babel-node –e js  

Add babel configuration inside a new file .babelrc as shown below to run our ES6 code to compatible code in server 

{ “presets”: [“env”, “stage-0”] } 

Finally, we need to create an index.js file which we used in start script of package.json. We can name it differently but the same should be used in package.json. 

Section 1:[index.js] 

Import express from ‘express’; 
const app = express(); 
const port = 3000; 
app.listen(PORT, () => { 
console.log(`Server is running on port ${PORT}`); 
}); 

Run npm start in the terminal and observe that server is running. 

Note: To get mock data in json, we can use https://www.mockaroo.com/ which we are going to serve from the server. 

Section 2: Let's extend the express app to add data to the server. 

  • Create a new folder ‘data’ and create a data.json with around 25 records of mock data. 
  • In Index.js file, import this data 
import data from './data/data.json' 
  • Under the console.log in the callback of app.listen, lets console.log this data. 
console.log(data); 
  • If you haven’t stopped the server, you will see the data in the console.log as nodemon is refreshing it on saving.  
  • If you run localhost:3000, you will see that data is not sent to the front end, they are still in server. 

Section 3:  Creating a route, which is responsible for getting your page or data requested from the server. There are basically four methods  GET, POST, DELETE and PUT. It follows a request-response paradigm. 

  • When we type in localhost:3000 in a browser, we see ‘Cannot Get /’ displayed because the default route is Get command. 
  • Lets add the route for ‘/’. 
app.get('/', (req, res) => 
    // get data first 
    res.send(`get request called on PORT: ${PORT}`); 
); 
  • Test in a browser and observe that a response has been displayed in the browser. 
  • Similarly we can do same for other methods i.e POST, PUT and DELETE. 
app.post('/newItem', (req, res) => 
    // get data first 
    res.send(`post request called on PORT: ${PORT}`); 
); 
app.put('/item', (req, res) => 
    // get data first 
    res.send(`put request called on PORT: ${PORT}`); 
); 
app.delete('/item', (req, res) => 
    // get data first 
    res.send(`delete request called on PORT: ${PORT}`); 
); 
  • We can test this method using POSTMAN. (www.getpostman.com
  • Select POST method and type localhost:3000/newItem -> Click Send 
  • Select PUT method and type localhost:3000/item -> Click Send 
  • Select DELETE method and type localhost:3000/item -> Click Send 

Note: We can insert body via POST Man and another cool feature of the postman is ‘code’ option.  We get the API calling in our preferred language. 

Section 4: Now instead of sending a simple text, let us send some data actually. 

  • Replace the string with data we had from data.json file. Normally, we make a DB call and return the response. 
app.get('/', (req, res) => 
    // get data first 
    res.json(data) 
); 
  • Test the same in a post and observe that data is displayed. The same thing can be viewed from the browser as well.  
  • So basically, we can use any of the front modules like react to build a useful view. 

Section 5: Some times, we need to serve some static files like CSS, HTML, images etc. 

  • Create a new folder ‘Images’ and copy the images from your pictures folder [for windows - Libraries\Pictures]. 
  • Here we are going to use express.static inbuilt method to add a static path to the server. 
app.use(express.static('public')); 
For now, think that ‘use’ is a method that allows adding specific middleware. 
  • ‘Use’ method basically takes the first argument as the route and if it is not provided then it would correspond to the default route ‘/’. 
  • Check and add some files to a public folder, for now, an image. Now switch to the browser and enter localhost:3000/[file name in public folder]. The browser should display that image. 
  • Similarly we can provide images as static 
And app.use('/images', express.static('images')); 
  • Now browser to localhost:3000/images/[imageName] and should display that image. 

Complete code till this point: 

importexpressfrom'express'; 
importdatafrom'./data/data.json'; 
constapp = express(); 
constPORT = 3000; 
// This is for the public folder on path / 
app.use(express.static('public')); 
// this is for images folder on path images 
app.use('/images', express.static('images')); 
app.get('/', (req, res) => 
// get data first 
res.json(data) 
); 
app.post('/newItem', (req, res) => 
res.send(`post request called on PORT: ${PORT}`); 
); 
app.put('/item', (req, res) => 
res.send(`put request called on PORT: ${PORT}`); 
); 
app.delete('/item', (req, res) => 
res.send(`delete request called on PORT: ${PORT}`); 
); 
app.listen(PORT, () => { 
console.log(`Server is running on port ${PORT}`); 
console.log(data); 
}); 

Section 6: Route parameters 

Till now, we played around with routes without parameters. Now we will extend this example to consider routing parameters. 

  • Try to get an item by id from the mock data, for which we need to provide a route with path item and id as parameter. 
app.get('/item/:id', (req, res, next) => { 
    // extract the parameters and all parameter are converted to string 
    console.log(req.params.id); 
   // Conversation to number 
    let user = Number(req.params.id); 
    console.log(user); 
    // retrieve the specific user based on id from out mockData. 
    console.log(data[user]); 
    res.send(data[user]); 
}); 
  • Now test by entering localhost:3000/item/04 and see that corresponding data is retrieved by comparing with the data in data.JSON file. 
  • The same thing can be observed in the terminal because of the console.log. 
  • We can also send multiple parameters like say we want to categorize the item further like ‘item/:category/:id’. 

Route Handlers: 

  • We have been using Route handler all this time without knowing it. The code gets called inside the callback is called route handler. 
app.put('/item', (req, res) => 
    res.send(`put request called on PORT: ${PORT}`); 

); 

  • Imagine if you want to handle multiple route handlers in a single route. For this, in express, we have something called next which is 3rd argument used above. 
  • For the same route of ‘item/:id’, lets add another handler. 
app.get('/item/:id', (req, res, next) => { 
    … //previous code 
    next(); 
}, (req, res) => { 
     console.log(‘Data is returned’); 
}); 
  • ‘next’ should always be called when we work using middleware otherwise the request is not processed further. 
  • Navigate to the same URL to get the specific item and observe data is displayed in the browser. 
  • Also, look into the terminal to see data is returned to acknowledge that an extended route handler is called. 
app.get('/item/:id', (req, res, next) => { 
console.log(req.params.id); 
letuser = Number(req.params.id); 
console.log(user); 
console.log(data[user]); 
res.send(data[user]); 
next(); 
}, (req, res) => 
console.log('Did you get the right data?') 
); 

We have a few common methods on the response object which we need to understand before using them. For example, till this point we used res.send and res.json to return the data from the server. It is important to understand the difference.  

  • Send method is for sending the response and has the intelligence to set the content-type based on the content sent. For example, is body is a buffer the content type is application/octet-stream. But if that is so then why do we need res.json.  
  • JSON method internally uses the send method but does some formatting based on options like replacers and spaces before calling the send method so that the client can directly consume it. 
  • There is another res.end method which as names suggest it ends the session. It is useful if we don’t have any data but just to set status and end. For data cases, we can rely on send and JSON method which will end as well.  
  • We have res.redirect to redirect our page to new page like res.redirect(‘www.nodejs.org’); 
  • For downloading the files from servers, we can use res.download. This is very similar to res.sendFile which allows does the same. 

For other methods refer to response methods here: http://expressjs.com/en/guide/routing.html 

Sometimes we need to have different methods for the same route like app.get(‘/item’), app.put(‘/item’) and app.delete(‘/item’). We can chain all of this together as shown below: 

app.route('/item') 
    .get((req, res) => { 
        res.send(`a get request with /item route on port ${PORT}`) 
    }) 
    .put((req, res) => 
        res.send(`a put request with /item route on port ${PORT}`) 
    ) 
    .delete((req, res) => 
        res.send(`a delete request with /item route on port ${PORT}`) 
); 

We are using the app.route method to create chainable route handlers for a route path. 

Template engines: Express provides support to a lot of template engines ‘out-of-box’. We can refer to them here - https://expressjs.com/en/resources/template-engines.html 

Out of this, some of the most popular are Pug, hbs, ejs. Let’s compare hbs and pugs. 

Hbs – syntax is similar to html template just that variables are in double curly braces.

<div class=’entry’> 
<h 1>{{title}}</h 1> 
</div> 
Pub (jade) – is kind of new syntax and uses white space for differentiation. It is lot smaller. 
.entry 
h1=title 

Let us take any of the above examples and implement templates. 

  • First we need to set the ‘view engine’ with our interested template engine say pub. 
const express = require('express'); 
const path = require('path'); 
const app = express(); 
app.set(‘view engine’, ‘pug’); 
  • Now express will take care rest but we need to say where it has to look for templates. 
  • Create a new folder called ‘views’ and set it as views to look for.  
app.set(‘views’, path.join(__dirname, ‘./views’)); 
  • Since we have given folder path, express assumes that index file exists and loads it accordingly. 
  • Let us create an index.pug file and add some basic html content. 
doctype html 
html 
    head 
    body 
        h1 Index Page 
        p This is the index page 
  • Now the route has to know that it has to render this page accordingly. 
app.get(‘/’, (req, res, next) => { 
return res.render(‘index’); 
}); 
  • Start the server and observe that the template is rendered correctly. Now, look into the HTML generated using developer tools, which is optimized by removing white spaces. 
  • If we want to generate the html in a readable format, we can enable a flag for development environment only. 
app.locals.pretty = true; 
  • res.locals is an object where we can add new fields in specific route and use them in the *.pug file. To illustrate this, let’s use a middleware to listen to error. 
app.use((err, req, res, next) => { 
res.locals.message = err.message; 
    const status = err.status || 500; 
    res.locals.status = status; 
res.locals.error = err; 
    res.status(status); 
    return res.render('error'); 
}); 
  • Update the *.pug file to display error message if error occurs.  

[we can convert an existing error page to pug format through some of the online converters] 

doctype html 
html 
    head 
    body 
        h1 Index Page 
        p This is the index page 
        if (error) 
h1.mr-3.pr-3.align-top.border-right.inline-block.align-content-center=status 
      .inline-block.align-middle 
        h2#desc.font-weight-normal.lead=message 
        pre=error.stack 
constexpress = require('express'); 
constcreateError = require('http-errors'); 
constpath = require('path'); 
constapp = express(); 
app.set('view engine', 'pug'); 
app.locals.pretty = true; 
app.set('views', path.join(__dirname, './views')); 
app.get('/', (req, res, next) => { 
returnres.render('index'); 
    }); 
app.use((req, res, next) => { 
returnnext(createError(404, 'File not found')); 
}); 
app.use((err, req, res, next) => { 
res.locals.message = err.message; 
conststatus = err.status || 500; 
res.locals.status = status; 
res.locals.error = req.app.get('env') === 'development' ? err : {}; 
res.status(status); 
returnres.render('error'); 
}); 
app.listen(3000); 

Leave a Reply

Your email address will not be published. Required fields are marked *

Suggested Tutorials

JavaScript Tutorial

JavaScript is a dynamic computer programming language for the web. JavaScript was first known as LiveScript. Later on, Netscape changed its name to JavaScript because of its popularity and the excitement generated by it. JavaScript is lightweight and most commonly used as a part of web pages supported by most web browsers like Chrome, Internet Explorer, Opera, Safari, Edge, and Firefox.
JavaScript Tutorial

JavaScript is a dynamic computer programming language for the web. Jav...

Read More

Angular JS Tutorial

Introduction: Angular  (What is Angular?)Angular was formerly introduced by Google corporation in 2012 and was considered to be one of the most promising among JavaScript frameworks. It was written completely in JavaScript to separate an application’s logic from DOM manipulation, aiming at dynamic page updates. Angular introduced many powerful features enabling the developer to effortlessly create rich and single-page applications.Topics CoveredThis Angular tutorial will span over eight modules, each module covering numerous individual aspects that you need to gain complete information about Angular. This set of modules serves as an Angular tutorial for beginners along with experienced IT professionals.Here are the topics that will be covered in the Angular tutorial:Get started with Angular.Learn the basics of Angular.Know what Angular Directives.Get an idea of Component Inputs and Outputs of Angular.Know about Forms in Angular.About Services in Angular.Pipes in Angular.HTTP, Routing and Building in Angular.Who can benefit from this tutorial?This Angular tutorial will be helpful to IT professionals such as:Software Developers, Web Application Programmers and IT Professionals Software Architects and Testing Professionals Career aspirants in web development
Angular JS Tutorial

Introduction: Angular  (What is Angular?)Angular was formerly introdu...

Read More

USEFUL LINKS