Node.js - Express Framework
Express is a minimal and flexible Node.js web application framework which provides a robust set of features for web and mobile applications. It is based on the Node.js middleware module which is called connect which in turn uses http module. So, any middleware which is based on connect will also work with Express.js.
Features of Express.js are:
- Makes Node.js is web application development which is very fast and easy.
- It is easy to configure and customize.
- It allows defining routes of your application based on HTTP methods and URLs.
- It is easy to integrate with different templates engines e.g jade, vash, EJS etc.
- It allows defining an error handling middleware.
- It allows you to create REST API server.
- It is easy to connect with a database such as MongoDB, Redis, MySQL.
Install Express.js we can install express.js using npm. The command shown below will install express.js globally on your machine.
The following command will install express.js local to your project folder
C:\myProject> npm install express –save
The above command saves the installation locally in the node modules directory and it creates a directory express inside node modules. We can install the following important modules along with express.
- Body-parser− this is a node.js middleware for handling JSON, Raw, Text, and URL encoded form data.
- Cookie-parser− Parse Cookie header and populate req.cookies with an object keyed by the cookie names.
- Multer− this is a node.js middleware for handling multipart/form-data.
Example:
The following app is a very basic Express app which starts a server and listens on port 8081 for connection. This app responds with Hello World! For requests to the homepage.
I have taken js file named as app.js
Run the above code node app.js
Configure Routes in Express.js
Use app object to define routes of your application. The app object includes get(), post(), put() and delete() methods to define routes for HTTP GET, POST,PUT and DELETE requests respectively.
Run the above example using node app.js command, and point your browser to http://localhost:3000 and you will see the following result.
Handle POST Request:
Create an index.html file in the root folder of your application and write the HTML code.
To handle the HTTP POST request in Express.js, we need to install middleware module called body-parser. The middleware was a part of Express.js earlier but now we have to install it separately.
This body-parser module parses the JSON, buffer, string, and url encoded data submitting using HTTP POST request.
Run the above code localhost:3000
Fill the First Name and Last Name in the above example and click on submit.