Express.js – app.use() Method

Express JSServer Side ProgrammingProgramming

The app.use() method mounts or puts the specified middleware functions at the specified path. This middleware function will be executed only when the base of the requested path matches the defined path.

Syntax

app.use([path], callback, [callback])

Parameters

  • path − This is the path for which the middleware function is invoked. A path can be a string, path pattern, a regular expression or an array of all these.

  • callback − These are the middleware functions or a series of middleware functions that acts like a middleware except that these callbacks can invoke next (route).

Example 1

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

// app.use() 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;

// This method will call the next() middleware
app.use('/api', function (req, res, next) {
   console.log('Time for main function: %d', Date.now())
   next();
})

// Will be called after the middleware
app.get('/api', function (req, res) {
   console.log('Time for middleware function: %d', Date.now())
   res.send('Welcome to Tutorials Point')
})

// App listening on the below port
app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});

Now, hit the following Endpoint with a GET request

http://localhost:3000/api

Output

C:\home\node>> node appUse.js
Server listening on PORT 3000
Time for main function: 1627490133904
Time for middleware function: 1627490133905

Example 2

Let’s take a look at one more example.

// app.use() 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;

// This method will call the next() middleware
app.use('/', function (req, res, next) {
   console.log('Middleware will not be called')
})

// Will be called after the middleware
app.get('/api', function (req, res) {
   console.log('Time for middleware function: %d', Date.now())
   res.send('Welcome to Tutorials Point')
})

// App listening on the below port
app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});

Now, hit the following Endpoint with a GET request

http://localhost:3000/api

Output

C:\home\node>> node appUse.js
Server listening on PORT 3000
Middleware will not be called
raja
Published on 01-Oct-2021 06:25:03
Advertisements