1.

Explain in detail the use of response object in Express?

Answer»

The response object or the res object, is used to send the data back to the client. It generally happens after the request is sent from the client in the req object. So, it is a part of the request and response cycle. 

Now, with the res object we have many methods like send(), status(), append(), redirect() and render(). We will look at some of them through an example. 

We need to FIRST create a simple Node.js PROJECT and install express in it. We will do it by creating a new folder and then changing to it. After that, giving the command npm init -y to create a Node.js project. After that we will install express in the app by giving npm i express command. 

Now, create a file server.js and add the below code in it. First, we are doing the required imports and listening on PORT 3000 for incoming requests. Now, with req.send we can send any data, when the user comes to the / route. 

Now, when we go to the / directory from the browser, we will get Hello Express shown. 

Next, we will look at res.redirect, which will redirect any route to the other route. In our case if we go to /help, we will be redirected to /user. 

Now, when we go to localhost:3000/help we will be redirected to HTTP://localhost:3000/user in the browser and will see the user PATH text.  

We have also created a route in which if we go to any route other than the one done earlier, we will get Page Not Found text and also a status of 404 will be sent. We are using both res.status() and .send() chained to it. 

Now, go to any non-existent route and we will shown Page Not Found text.  



Discussion

No Comment Found