If you know NodeJS, Express Frameworks comes with it.
What is Express?
Express is a node.js framework that is used to build web application. With Express framework it makes it a lot easier to be able to handle multiple requests such as GET, PUT, POST and DELETE.
Installing Express
Before installing express, make sure to complete installing node.js on the system. Once done, you can follow the below steps to install express.
npm install express
Following the installation you want to require it on top of your App.js File.
const express = require('express')
Why use Express over normal NodeJS?
1. Easier to create web application and services.
2. Easier Routing to Modules
3. Consistent Middleware interface
4. Easier to handle data, post data, session management and more.
How to create
To create a simple express example, first lets create a directory where you want to be able to save your code
mkdir expressApp // Make a directory to save all codes
cd expressApp // Enter the directory
After creating the directory and entering the directory we want to be able to create a package.json file by using the command line npm init
and following install Express in the local directory.
npm install express
Running the code:
const express = require('express');
let app = express();app.get('/', function (req, res){
res.send('Response recorded for Homepage');
})
;app.listen(3000, function () {
console.log('app is running on port 3000');
});
In your terminal run this code:
node App.js
In your browser type in this URL:
localhost:3000/ //To check if everything works
Body-Parser
We also need Body-Parser to be able to handle HTTP POST
request in Express.
Install Body Parser
npm install body-parser — save //To installed body-parser
Body-Parser in your App.js File
const express = require(‘express’),
app = express(),
bodyParser = require(‘body-parser’);// support parsing of application/json type post data
app.use(bodyParser.json());//support parsing of application/x-www-form-urlencoded post data
app.use(bodyParser.urlencoded({ extended: true }));