1.

What function as arguments are available to ExpressJS route handlers?

Answer»

There are three functions, which are available as arguments in Express.js ROUTE HANDLER function. The route handler functions are GET, post, put, delete, and others. These are mentioned below. 

  • req - It is known as the request OBJECT, which is a callback function. In Express we receive the DATA from the client, using three different types of requests. They are req.params, req.query and req.body. 
  • res - It is also known as the response object. It is used to send the response back to the client. With the res object you can send many types of responses, like res.send, res.render, res.download and more. 
  • next - It is an optional callback function, which can be used to send the control to the next middleware or function. 

We will take a small example containing all three arguments. We need to create a Node.js application first by creating a folder and adding node by npm init -y command. 

After this, we will install express in it using npm i express command.

Next, we’ll create a file with the name server.js and add the below code in it. Here, we shall first see the use of next() to pass control to the next function. After that with res.send() we will send the text Node.js Developer to the client. 

We also have a route to get the id of the user with req.params.id. 

Now, start the server with node server.js from the command line and then go to http://localhost:3000/ in the browser. We will see the below messages in the terminal.

Also, if we go to the route like http://localhost:3000/22, we will get the below console log in the terminal.  



Discussion

No Comment Found