Express framework in Node.js
The express.js
is a web application framework for Node.js. It is a framework that acts as server application to handle api calls from client. It can serve static files and resources of your application as well as act as REST API server.
How to install express?
npm install -g express
The above command will install express.js
globally on the machine. The advantage of installing express globally is that, every nodejs application can use it.
If you want to install express to a particular application alone then
npm install express --save
Create a file index.js
and add the following code.
const express = require("express");
const app = express();
const port = 8000;
app.listen(port, function() {
console.log(`Server running in port ${port}.`);
});
Output
Server running in port 5000.
In the above program, express.js
module is imported to a variable express using require()
function. The express module would return a function. This function is now applied to the object app by calling express()
function.
Now the object app includes get()
, post()
, put()
and delete()
function. These function are used to handle get
, post
, put
and delete
api calls. In addition to these function the app object has a function listen()
, which listens to a particular port.
Next, modify the program which contains all the above functions.
const express = require('express');
const app = express();
const port = 8000;
app.get('/get-call', (req, res) => {
res.send('Get request call.');
});
app.post('/post-call', (req, res) => {
res.send('Post request call.');
});
app.put('/put-call', (req, res) => {
res.send('Put request call');
});
app.delete('/delete-call', (req, res) => {
res.send('Delete request call');
});
app.listen(port,() => {
console.log(`Server running in port ${port}.`);
});
Output
Server running in port 5000.
Now our first program in nodejs with express framework is ready to run. To run the program we use.
node index.js
The program is now running on port 5000 and can handle 4 api calls. To check whether the program can serve the api we can simple call the get
api call in the browser.
http://localhost:5000/get-call
This will respond with Get request call.
in the browser.
Similarly we can call the rest of the api with any tool. One the popular tool for testing the api calls is postman
.