Express.js – router.METHOD() Method


The router.METHOD() is used for providing the method functionality in Express, where METHOD represents one of the HTTP methods such as GET, POST, PUT, and so on, in lowercase. Therefore, the actual methods are represented as following −

  • router.get()

  • router.post()

  • router.put() …… and so on...

Syntax

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

Example 1

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

// router.METHOD() Method Demo Example

// Importing the express module
const 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 single endpoint
router.get('/api', function (req, res, next) {
   console.log("GET request called for endpoint: %s", req.path);
   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 routerMETHOD.js Server listening on PORT 3000 GET request called for endpoint: /api

Example 2

Let's take a look at one more example.

// router.METHOD() Method Demo Example

// Importing the express module
const 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 single endpoint
router.get('/api', function (req, res, next) {
   console.log("%s request called for endpoint: %s", req.method, req.path);
   res.end();
});

router.post('/api', function (req, res, next) {
   console.log("%s request called for endpoint: %s", req.method, req.path);
   res.end();
});

router.delete('/api', function (req, res, next) {
   console.log("%s request called for endpoint: %s", req.method, req.path);
   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 – localhost:3000/api
POST – localhost:3000/api
DELETE – localhost:3000/api

Output

C:\home
ode>> node routerMETHOD.js Server listening on PORT 3000 GET request called for endpoint: /api POST request called for endpoint: /api DELETE request called for endpoint: /api

Updated on: 28-Mar-2022

129 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements