1.

Write the steps for setting up an Express.js application?

Answer»

An Express.js app is basically a Node.js app, with express installed in it. We have to create a basic Node.js app and then add express to it, which is available as an external npm package.

So, open any terminal and create a directory and then navigate to the directory using the cd command. After that create an NPM project by giving npm init -y command. If we omit the -y flag, we have to RESPOND to some questions manually with ‘yes’.

Next, we need to install the express package through npm. 

Now, create a FILE index.js in the route directory and add the below lines in it. The first line is used to import the express MODULE, which we have just installed. The SECOND line is used to create our app variable, using express. We are going to use this app variable throughout our app.  

The next lines of code tell that we are doing a GET request, using the app which we have previously created. It takes two parameters and the first one tells the path on which this action will be taken. It is also known as route and it is ‘/’ in our case. 

The next argument is “req” and “res”. Here, the ‘req’ is the request which was sent to the server and the ‘res’ is the response, which will be sent back from the server. We will be sending back a simple text of Hello Express to the client.

Lastly, we will listen to some port for the request. We generally listen to port 3000 for backend, but we can take any port. Also, notice that we have a second argument to listen function, which is generally used for logging.Now, we will start the server from the terminal by giving the command node index.js and we will get the output of the log.

Lastly, in any BROWSER go to http://localhost:3000/ and you will see the response from the server.  




Discussion

No Comment Found