router.all() Method in Express.js


The router.all() method matches all the HTTP Methods. This method is mainly used for mapping "global" logic for specific path prefixes and arbitrary matches.

Syntax

router.all( path, [callback, ...] callback )

Example 1

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

// router.all() 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;

// Setting the single route in api
router.all('/user', function (req, res) {
console.log("Home Page 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 − http://localhost:3000/user

Output

C:\home
ode>> node routerAll.js Server listening on PORT 3000 Home Page is called

Example 2

Let's take a look at one more example.

// router.all() 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 routes
router.all('/home', function (req, res) {
   console.log("Home Page is called");
   res.end();
});
router.all('/index', function (req, res) {
   console.log("Index Page is called");
   res.end();
});
router.all('/api', function (req, res) {
   console.log("API Page 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 with a GET request −

  • http://localhost:3000/home

  • http://localhost:3000/index

  • http://localhost:3000/app

Output

C:\home
ode>> node routerAll.js Server listening on PORT 3000 Home Page is called Index Page is called API Page is called

Updated on: 29-Jan-2022

357 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements