To install express, write the command npm i express. Now, before using express I would recommend you to install postman for API testing.
How to use express?
The first step is to write npm init command in the terminal to create a new Node.js project by generating a package.json.
Let’s see a simple example of using express.
const express = require('express'); const app = express(); app.get('/', (req, res) => { res.status(200).json({ display: 'welcome', name: 'codeyup', }); }); const port = 8000; app.listen(port, () => { console.log(`current port: ${port}`); });
You can now check the API response in the browser network tab or using the postman. I have attached a image below in which I used postman for checking the above GET API call response.
Explanation:
- Import express in app.js file and now create a variable with any name such as app and assign express() function to this variable. This function will add a bunch of methods (such as get, post, etc) to the variable app.
- app.get is used for GET requests to the root URL (‘/’). When a GET request is made to ‘/’, the provided callback function is executed.
- req (request) contains information about the HTTP request.
- res (response) is used to send a response back to the client.
- Inside the callback function, we set the HTTP status code of the response to 200 (i.e success) and send a JSON response with two properties: display with the value ‘welcome’ and name with the value ‘codeyup’.
- In variable port, I have given the value 8000 and this port number will be used by the Express application to listen for incoming connections.
- I used app.listen() to start the server and makes it listen for connections on the specified port (8000).