router.route() Method in Express.js


The router.route() method returns the instance of a single route which can be used to handle the HTTP verbs further with the optional middleware. This method can be used to avoid duplicate route naming and therefore the typing errors.

Syntax

router.route( path )

Example 1

Create a file with the name "routerRoute.js" and copy the following code snippet. After creating the file, use the command "node routerRoute.js" to run this code as shown in the example below −

// router.route() Method Demo Example

// Importing the express module
var express = require('express');

// Initializing the express and port number
var app = express();

// Initializing the router from express
var router = express.Router();
var PORT = 3000;

// Defining a route
router.route('/api')
.get(function (req, res, next) {
   console.log("GET request - /api endpoint is called");
   res.end();
});
app.use(router);
app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});

Hit the following Endpoint with a GET request − localhost:3000/api

Output

C:\home
ode>> node routerRoute.js Server listening on PORT 3000 GET request - /api endpoint is called

Example 2

Let's take a look at one more example.

// router.route() Method Demo Example

// Importing the express module
var express = require('express');

// Initializing the express and port number
var app = express();

// Initializing the router from express
var router = express.Router();
var PORT = 3000;

// Defining Multiple routings
router.route('/api')
.get(function (req, res, next) {
   console.log("/api -> GET request is called");
   res.end();
})
.post(function (req, res, next) {
   console.log("/api -> POST request is called");
   res.end();
})
.put(function (req, res, next) {
   console.log("/api -> PUT request is called");
   res.end();
});
app.use(router);
app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});

Hit the following Endpoint one by one −

  • GET Request −localhost:3000/api

  • POST Request −localhost:3000/api

  • PUT Request −localhost:3000/api

Output

C:\home
ode>> node routerRoute.js Server listening on PORT 3000 /api -> GET request is called /api -> POST request is called /api -> PUT request is called

Updated on: 29-Jan-2022

921 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements