InterviewSolution
| 1. |
Explain in detail the use of request object in Express.js? |
|
Answer» The request object is used to handle the DATA which comes to the server through string or JSON object. Express will receive data from clients through three types of req objects i.e., req.params, req.query and req.body. We will learn in detail about it through examples. First, we shall 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, we will create a file server.js and add the below code in it. First, we are doing the required imports while also listening on PORT 3000 for incoming requests. Now, with req.params we can get the data passed in the url. Now, go to http://localhost:3000/22 in any browser and we will see the id in the running server. We generally get the data from the client in a POST request through a JSON object. We will add a new /login path in which we are console logging the email and PASSWORD from req.body. NOTICE that we need to use a middleware of app.use(), so that we can receive json. Also, we need to send back a success request with res.send() to the client. Now, we need to send a POST request through Postman, or else create a frontend and take the data from the user and submit it as a JSON object. In Postman, we send a JSON object with email and password. Now, with the server running, we will get both email and password received on the server. |
|