Node Js Express

Learn via video courses

Overview

Nodejs comes with a lot of inbuilt core modules and utilities. These can help you create an app, but that will be laborious and difficult. Thus we have a great alternative, which is the Express js framework which is built on top of the http core module and provides us with a lot of handy features and utilities to make the development process simple and faster than ever.

Pre-requisites

You will need to have the pre-requisite to follow along with the article :

  • Node js and npm should be installed locally on your system. You can download Node from their official website.
  • Basic understanding of javascript functions, variables, and syntax along with knowledge of HTTP.

Introduction to Express Framework

Express js framework is small, open-source, free, and was released in 2010. Technically express is built with the help of the Node js core module http to make the development cycle less time-consuming and easy. It is essentially the standard framework used for server (backend and API services) development for Node js and is currently on version 4.0 with version 5.0 in the beta testing phase.

Express provides you with a set of utilities in the form of handlers, routers, controllers, middleware, and many more by using the core modules of Node.js under the hood. Also, there is no restriction on how to use these utilities to create your backend services. Hence the express framework comes with everything you need to start the development process efficiently.

Why Use Express?

Some of the advantages of using Express over other backend services are :

  • Simple to learn: The most obvious advantage of using Express is that it is written in Javascript. As javascript is one of the most famous languages and is widely used in developing web applications, it will be worthwhile and easy to adapt to the express framework.
  • Same language for backend and frontend: Another benefit is that there would be a single stack (written in javascript) that will be used to develop both the front end and the back end of the application. Although it is possible to write frontend and backend in different frameworks it can be quite difficult to work with.
  • Scalable: Express allows you to scale your application efficiently. As we know, there is the support of clusters and process in Node.js to interact with worker threads. We can easily scale the Node js express application using some additional extra resources.
  • Community: The community support ecosystem is very vast. Hence if you are ever stuck somewhere, there are different extensions available in the form of middleware (third part libraries) to add different kinds of functionality so that you can complete your job.
  • Caching: Server-side caching is also supported by Express.js, which increases performance and efficiency. Also, this feature helps pages to load faster.

Nodejs Example:

Nodejs Express Example

Installing Express

Now, as we have gone through express and its importance, let’s start working with nodejs express. The first step will be to install express. Follow the below steps to install express in your system:

  1. Let us create a directory in which you will start your Node.js express project.

Now navigate to the created directory:

  1. After navigating to the project folder, run the below command:

The above command is used to initialize a Node.js project. A series of questions will be asked about the project. After that, a package.json file containing the information about the project will be created.

  1. Now install the Express package using npm :

The above command will install express. A node_modules folder will be created on completion. The package.json file will have express and its version mentioned in the dependencies.

Example: Helloworld Express

After installing express, let us create a small express app. Create a server.js file in the project directory and write the following code in it:

Now save the file and execute the below command to run the code:

When the app will start you will get the following message in the terminal :

Now open localhost:8080 in a web browser, and you will see the following output :

Output-1

Importing and Creating Modules

A module is an encapsulated piece of code that we can import anywhere in other parts of the project. A module can be imported with the help of the require() function.

The syntax is shown

Express is a third-party module

First, we have to import the module and then invoke the returned object to create the express application.

We can similarly import other modules:

We can also create modules and import them in a similar way. To export a function or variable, we have to make use of the exports object. exports object is a reference to module.exports where module is global. The syntax is as follows :

Let’s create a file util.js and export a set of functions in the file :

We can now import the functions in any other file as shown :

Now all these functions can be used in the current file.

Request & Response

The express Request object represents the HTTP request and has properties like query string, body, headers, etc. The response object represents the HTTP response. It is used to send a response back to the browser or add cookies values in the client’s browser.

Example:

Output:

Basic Routing

Routing defines how an application responds to an HTTP request method(GET, POST, etc.) on a certain path (or URI ). Every route is associated with one or more handler functions. The handler functions are used to define the logic for that route.

Basic Routing

The definition of a route can be generalized as follows :

Description of the above code :

  • app - express instance.
  • METHOD - HTTP request method.
  • Route_path - path on the server.
  • Handler_function - Function that is associated with given route options.

Let us have a look at some examples :

  • An endpoint for the GET request at the / route.

  • An endpoint for the POST request at the /user route.

  • An endpoint for the PUT request at the /user route.

  • An endpoint for the DELETE request at the /user route.

Using Asynchronous APIs

In synchronous operations, the execution of the main thread is blocked until the operation is complete. The next operation starts only when the current is completed.

For example, in the above code, the first console.log() will execute, and after that, the second will execute.

In asynchronous APIs, the operation is placed in the event queue, and the main thread is not blocked. This way, asynchronous APIs are handled. This speeds up the application and also improves efficiency. If we place the first console.log() in a setTimeout() function, the output will get reversed :

Output:

We can use async await or promises to handle asynchronous operations. Let's have a look at a handling function that uses promises to work with asynchronous code.

In the above code snippet, let's assume queryDB() is a function that queries data from the database is used, on completion of this operation the .then handler is called and it receives the output of queryDB(). This continues further along the promise chain.

Another way of doing the above operation is using async-await, where we can make the function async and complete the promise using await.

Let us have a look at that.

Serving Static Files

Static files like images, html files, or other media can be served using the express middleware express.static(). The syntax to use this middleware is :

Where root is the path of the folder with static files and options is an object that has various properties like setHeaders, dotfiles etc.

Assume you want to serve the static files in the directory public then. You will have to add :

The files are served at the base URL combined with the path of the file relative to the static files folder.

For example, if an image sample.png is stored in static files folder, then it can be accessed at :

localhost:8080/sample.png

If the CSS file is in the static/style folder, then :

localhost:8080/style/styles.css

We can use express.static() multiple times for multiple folders. If a file is not found in the first folder, then the second middleware will be executed.

We can also create a virtual prefix like:

Now static files will be at the /file path.

Handling Errors

For handling errors, the middleware functions with four parameters are used. The four arguments are: err (error), req (request), res (response), and next (next middleware function).

This middleware should be used after all the routes and other middleware so that if no middleware can handle the request, then the error is handled.

Express also has a built-in error handler. If none of the described middlewares can handle the error, then the express built-in handler sends the error message to the fluent with the stack trace.

GET Method

The HTTP Get method is used to fetch a resource from the server. It can pass a limited amount of data as URL parameters. Let us make use of the GET method with the help of express.

In the server.js file, write the following code :

Create a file form.html to make a small form as below :

The output of the form.html will be as shown :

Output-2

On pressing submit the webpage will show the following response :

Output-3

The server console will show the following :

In the above code the firstname and lastname are passed as query parameters and the request is handled by the get endpoint. The handler function gives the response as the fullname.

POST Method

POST method is used to send a large amount of data in the body of the request. The data is also secure as it is not visible in the URL.

Let us now implement the same example with the help of POST.

Write the following code in the server.js file.

Make changes in form.html as shown:

The above code will give similar output to GET, only the data won't be visible in the URL.

File Upload

Lets up look at how we can upload files using the POST method. index.html code will be as follows:

Let us now modify server.js to handle form data:

Now you can check the form on

http://127.0.0.1:8080/index.htm.

Output-4

Cookies Management

A small piece of data stored in the user's browser while the user is browsing that website is called cookies. This data is sent back to the server every time the user loads the website back to distinguish the user's previous activity. We use the cookie-parser package to use cookies in the nodejs express application. By using this package we can smoothly manage cookies.

Installing package for cookie management :

Syntax of cookie-parser :

Adding this middleware in the nodejs express app :

The above module gives up access to req.cookies with an object with a cookie name and its properties.

We can also use req.secret to enable signed support cookies by passing a secret string.

Setting cookies:

The maxAge option used in the above code is optional. Let us look at other options :

  • To set expiration time in milliseconds :
  • To set cookie only over HttpOnly :
  • To use an encrypted http channel for secure cookie data exchange :

Reading Cookies:

Users can access the cookie using the request object using: req.cookies or req.cookies.cookie_name.

Deleting Cookies:

We can simply delete cookies using the browser developer tool, or we can simply use the method res.clearCookie(). This function accepts a single argument i.e. name of the cookie to be deleted.

Using Databases

Nodejs express apps support many database services like MongoDB, SQL, SQLite, PostgreSQL, Redis and many more. Express itself does not define any extra particular conditions or behaviors for database management services. Database service can be cloud-based or present locally in your system. To use the above service providers, you need to install their driver and then connect your app with that database service.

Let us take an example of a MongoDB connection. Installing MongoDB driver :

Now let us connect the database to your Nodejs express app :

There is one other method known as Object Relational Mapper (ORM) through which we can access the database indirectly. This approach defines data in the form of models or objects, and ORM uses the underlying database format for mapping.

Rendering Data (Views)

Template engines are used for generating a fixed type HTML structure and many more types of documents where the dynamic code gets placed in the respective placeholders. These placeholders in the template format are pre-defined. Express js also refers template engine as a views engine.

Express engines supported by nodejs express are - Pug, Mustache, and EJS. To use a template engine, you need to define two things for express :

  • Which template engine name are you going to use, and
  • What is the location where express can find the templates or views to render?

Setting up the nodejs express app to use a view engine :

To use the template engine, we call the reponse.render() method and pass the filename along with the data object using variable_name: Data to be passed format.

File Structure

All of your application code can be present in a single javascript file, but it makes no scene as the code become difficult to manage and read. Hence we can say that express makes no belief in the folder structure of the app, and any file can go in any directory.

File Structure

However, we generally follow the standard MVC architecture, that is, model view controller structure. You can also use the Express Application Generator for creating a modular app skeleton that can be easily extended for creating web applications.

Conclusion

  • Express is open source and a fast web framework for Node.js.
  • Express provides you with a set of utilities in the form of handlers, routers, controllers, and middleware.
  • Routing defines how an application responds to an HTTP request method(GET, POST etc).
  • GET method is used to fetch data while the POST method is used to send data to the server.
  • Express servers static files using middleware express.static() also express has a built-in error handler.
  • We use async await or promises to handle asynchronous operations in nodejs express.
  • cookie-parser package is used for cookies handling in the nodejs express application.
  • Nodejs express supports many database services like MongoDB, SQL and template engines like pug, ejs etc.