What is Express.js?
1. What is Express.js?
Express.js is a free and open-source web application framework for Node.js and is used for designing and building web applications that are running on web browsers and organizing your back-end architecture. Express.js supports JavaScript which is a commonly used programming language. Without Express.js, you have to write your own code to build a routing component which is a time-consuming and tedious task. Express.js offers simplicity, flexibility, efficiency, minimalism, and scalability to programmers. It also has the advantage of powerful performance as it is a framework of Node.js.
2. Install and use Express.js
It can be installed via the Node Package Manager with the command “npm install express”. The basic use would be as below:
// use require function to import express module
const express = require('express');// create an object
const app = express();// create a callback function which is called when you access to "http://localhost:3000"
//"app" is an instance of the express moduleapp.get('/',function(req,res)
{
res.send('Hello World!');
});
const server=app.listen(3000,function() {});
3. Create a routing with Express.js
A routing defines the way in which your application responds to a client request to a particular endpoint. For instance, with Express.js a user can make a GET, POST, PUT or DELETE http request for various URLs such as
http://localhost:3000/admin
http://localhost:3000/student
Each route can have one or more handler functions which are executed whtn the routing path is matched. The syntax would be
app.METHOD(PATH, HANDLER)/* app : an instance of the express module
METHOD : an HTTP request method (GET, POST, PUT, or DELETE)
PATH : a path on a server
HANLDER : a function to be executed when the route matches*/
4. Why Express.js?
Here are some of the use cases of Express.js:
- Using cookies on a website
2. Implementing authentication
3. Adding a search bar to a site
4. Serving static files like images
Also there are several advantages to use Express.js:
- Allows development of Node.js web application simple and quick.
- Simple and easy to set up and customization.
- It lets you identify your application routes based on HTTP methods and URLs.
- It contains several middleware components that can be used on request and response to conduct extra duties.
- Easily integrates with various template engines such as Jade, Vash, EJS, etc.
- It helps you to identify a middleware handling error.
- Easily handle the application’s static files and services.
- It enables you to build a server with the REST API.
- Fast to link to databases like MongoDB, Redis, MySQL.