What is Express.js?
Expressjs is a Node js web application server framework, which is specifically designed for building single-page, multi-page, and hybrid web applications.
It has become the standard server framework for node.js. Express is the back end part of something known as the MEAN stack.
The MEAN is a free and open-source JavaScript software stack for building dynamic web sites and web applications which has the following components;
-
MongoDB – The standard NoSQL database
-
Express.js – The default web applications framework
-
Angular.js – The JavaScript MVC framework used for web applications
-
Node.js – Framework used for scalable server-side and networking applications.
Installing and using Express
Express gets installed via the Node Package manager. This can be done by executing the following line in the command line
npm install express
The above command requests the Node package manager to download the required express modules and install them in local project folder accordingly.
Here we are going to use installed Express framework and create a simple “Hello World” application.
Let’s create a simple server module which will listen on port no 3000.
In our example, if a request is made through the browser on this port no (‘http://localhost:3000’), then server application will send a ‘Welcome Express World’ response to the client.
//1.Use the express module
var express = require('express');
//2.Create an object of the epxpress module
var app = express();
//3.Create a callback function
app.get('/', function(req, res) {
//4. Send 'Welcome Express World' response
res.send('Welcome Express World !');
});
//5.Make the server listen on port 3000
var server = app.listen(3000, function() {
console.log('Listenint Port : 3000 ');
});
Explanation :
-
Load the ‘express module’ through require function
-
Create an object of express module
-
Create a callback function, which will be called whenever we browse (‘http://localhost:3000’) port.
-
When we browse the port, the server will execute the callback function and send the response as ‘Welcome Express World’ to the client.
This ‘res’ parameter is something that is provided by the ‘request’ module to enable one to send content back to the web page.