Express.js – app.route() Method


The app.route() method returns the instance of a single route. This single route can be used to handle the HTTP verbs with the optional middleware. This method is mainly used to avoid duplicate names.

Syntax

app.route( )

Example 1

Create a file with the name "appRoute.js" and copy the following code snippet. After creating the file, use the command "node appRoute.js" to run this code.

// app.route() Demo Example

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

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

// Creating a get, post & other requests
app.route('/user')
.get((req, res, next) => {
   res.send('GET is called');
   console.log('GET is called');
})

.post((req, res, next) => {
   res.send('POST is called');
   console.log('POST is called')
})
.all((req, res, next) => {
   res.send('All others are called');
   console.log('All others are called')
})

app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});

Hit the below endpoints/API to call the above function −

Output

C:\home
ode>> node appRoute.js '' '/api' '/api/v1'

Example 2

Let’s take a look at one more example.

// app.route() Demo Example

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

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

// Creating a get, post & other requests
app.route('/api/*')
.get((req, res, next) => {
   res.send('GET is called');
   console.log('GET is called');
})

.post((req, res, next) => {
   res.send('POST is called');
   console.log('POST is called')
})

.all((req, res, next) => {
   res.send('All others are called');
   console.log('All others are called')
})

app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});

For the above function, you can call any endpoint after /api/ and it will be passed through the above function only. For example,

Output

C:\home
ode>> node appRoute.js Server listening on PORT 3000 All others are called GET is called

Updated on: 30-Sep-2021

912 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements