Node.js

Getting Started With Node.js Express Framework

Google+ Pinterest LinkedIn Tumblr

In the last few years, Javascript gains so much popularity in the web development field. Today, Javascript stacks(MEAN/MERN) are so much popular than any other language stack for developing the web application. All the javascript stacks use Node.js as a server-side programming language. Express is one of the most popular and used frameworks for the node.js. It is used for building a scalable and robust web application using the node.js as a server-side language. In this tutorial, we are going into the deep understanding of the node.js express framework. We will learn how to create a server using the express framework, integrate template engine, understand express framework middlewares.

Create a Server In Node.js Express Framework

At the time of writing this tutorial, the latest version of the express is 4.16. So we will use this version in all this article and the Ubuntu operating system. The latest version of the node.js express framework contains important security updates and remove less used modules from the framework. Before moving to this article make sure you have node.js installed in your system.

To get started with the node.js express framework, we first need to install it and require it in your application. Create a new folder and go to that folder and type the below command to initiate the package.json file of our application.

npm init

Some of the few questions are asked after running above command. Fill all the details of your application. The important point between them is the entry point of the application. Give a  name your to entry point file as server.js or keep it as it is if you do not want to change the entry point file name. Default file name is index.js

Note: Entry point is the part of the application from where Express JS application started.

Now our package.json file is created, we can install express in our application by running the below command

 npm install express --save

Now create our entry point file server.js in the root directory of the project and copy the below code

const express = require('express'),
      app = express();

app.get('/',(request,response)=>{
  response.send('Hello Express!');
});

app.listen(3010,()=>console.log('node.js express server started at port 3010'));

Let’s understand what the above code is doing. Here, we imported the Express module from the node_module to our application using the express variable and then assign that to the app variable. Next, we use the HTTP get verb to handle the get request to the server. Express provides basic verbs of HTTP protocol to do HTTP operations. Then the last line of the above code tells Express to listen to all the request on the PORT 3010.

Routing In Express

Express routers are used as a middleware for assigning a specific function to respond to a client request. Node.js Express framework provides simple and easy to use server routing. Below is the basic format of routing in the Express framework

app.VERB(path,other_middlewares,callback);

In the above, path is the URL from to which request will come, VERB is any one of the HTTP methods like GET, POST, DELETE, PUT, PATCH, other_middlewares is used to authenticate the request or do other tasks before proceeding the request to the main function, callback is used to send the response to the client with appropriate status.

Request Object of the Router

Request object of the node.js express framework contains the following property

  • request.param: It stores the HTTP GET method parameters. For example, In the URL https://localhost:3010/param1/param2, we can get the param1 and param2 by using the request.param
  • request.body: It stores the HTTP POST method data. If you want to get the data of the form submitted by using the POST Method then you can easily get that by using request.body 
  • request.query: It stores the HTTP GET method data. If you want to get the data of the form submitted by using the GET method then you can easily get that by using request.query 
  • request.url: If you want to get the requested URL then you can get that by using this property of the request object.
  • request.ip: is used to get the IP of the requested browser.

There are so many properties of the request object apart from above property like request.headers and request.accepts

Response Object of the Router

Like Request object of the Express Router, Response object also has so many properties which we used frequently in the web application development.

  • response.send() is used to send the response to the browser.
  • response.json() send data to the client in the JSON format.
  • response.cookie(name,value,duration) is used to set the cookies on browser.
  • response.redirect([redirect status], URL) redirect the browser to the specified URL.
  • response.status() set the status of the response requested by the client.
  • response.render() renders the file to the browser.

Serve Static Files In Node.js Express Framework

To serve the static files like CSS, JS, Images in the express framework, we need to set the path in the express framework. It is good practice to store all the static files in the express framework in the Public folder. Let’s create a new folder in our application and set this path in our server.js file to serve these files.

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

Template Engines In Express Framework

A template engine helps to create the HTML file in the application using very minimal code. Template engines allow us to generate HTML dynamically by adding the variables in the runtime.

The following is a list of important template engines for Node.js Express Framework.

For this tutorial, we are going to use the handlebars template engine. To set this template engine we have to first install it and then tell express to use this template engine for rendering HTML.

Install the handlebars by running below command

npm install --save express-handlebars

Now we have to tell express to use this as a template engine by adding below code in our server.js file. After adding handlebars code, the server.js file looks like below

const express = require('express'),
           app = express(),
           hbs = require('express-handlebars').create({defaultLayout:'index.hbs'});

//setting our app engine to handlebars
app.engine('hbs', hbs.engine);
app.set('view engine', 'hbs');

app.get('/',(request,response)=>{
  response.render('main',{title: 'main page'});
});

app.listen(3010,()=>console.log('node.js express server started at port 3010'));

Create views folder in the root directory which contains all the template of our application. Inside the views folder, create layouts folder which contains our index.hbs file and create a homepage.hbs file in the view folder.

 <!--          index.hbs file   -->

<!DOCTYPE html>
<html>
	<head>
		<meta charset='UTF-8'>
		<title>{{title}}</title>
	</head>
	<body>
		{{{body}}}
	</body>
</html>
 <!-- homepage.hbs file -->

<h1>This is homepage of your express app</h1>

After creating above two files, go to your browser and type the URL http://localhost:3010, you will see a page like below in the browser.

handlebar-template-engine-in-express

You can find all the source code on github page of codesquery

Conclusion

Till now in this tutorial, we learn how to setup node.js express framework for the web application development. This is just the basic of the express framework. There is a lot of more things to do for the production environment like CORS, Authentications, Sessions, Cookies, error handling etc. Keep Visiting this blog to get more tutorials on the express framework.

Write A Comment

Pin It