How Do I Setup Express Web Server?
This is a quick guide on how to set up basic server with Express.js framework in Node web application.
So,let’s start by installing Express.js from command line.
npm install express
Create a new js file or on your main js file (the entry point of your web application) write the following code.
1. const express = require(“express”);
2. const app = express();
3. listen(3000, () =>
4. console.log(‘app listening on port 3000’),
5. ); On line 1 we imported Express module and assigned it to a variable constant express
On line 2 we executed Express function and assigned it to a variable constant app.
On line 3 we started sever by listening to request on port 3000.
When we listen to port 3000, callback function gets executed and console log ‘app listening on port 3000’.
If you have more than one app running and port 3000 is already assigned, you can listen to other port like 8080 or 3003.
Right now our server is running but it not handling any request so let’s send our first request.
Let’s try our server by sending a GET request.
app.get(‘/’, ( req, res ) => {
res.send(“HOME PAGE”)
})
Here we are sending GET request at root route.
Here, you can see that our callback function has two parameters req and res. You can name them anything but req and res is common. They are both objects created by Express on receiving incoming request.
First parameter (req) handles incoming request i.e data send to the server.
Second parameter (res) handles outgoing response i.e data returned from the server.