Express.js | app.use() Function – GeeksforGeeks

The app.use() function is used to mount the specified middleware function(s) at the path which is being specified. It is mostly used to set up middleware for your application. 

Syntax:

app.use(path, callback)

Parameters:

  • path: It is the path for which the middleware function is being called. It can be a string representing a path or path pattern or a regular expression pattern to match the paths.
  • callback: It is a middleware function or a series/array of middleware functions.

Installation of the express module:

You can visit the link to Install the express module. You can install this package by using this command.

npm install express

After installing the express module, you can check your express version in the command prompt using the command.

npm version express

After that, you can just create a folder and add a file, for example, index.js. To run this file you need to run the following command.

node index.js

Project Structure:

Filename: index.js 

javascript




const express = require('express');

const app = express();

const PORT = 3000;

 

app.use(function (req, res, next) {

    console.log("Middleware called")

    next();

});

   

app.get('/user', function (req, res) {

    console.log("/user request called");

    res.send('Welcome to GeeksforGeeks');

});

 

app.listen(PORT, function(err){

    if (err) console.log(err);

    console.log("Server listening on PORT", PORT);

});



Steps to run the program:

Make sure you have installed the express module using the following command:

npm install express

Run the index.js file using the below command:

node index.js

Output:

Console Output:

Server listening on PORT 3000

Browser Output:

Now open your browser and go to http://localhost:3000/user and you can see the following output on the console as shown below:

Server listening on PORT 3000
Middleware called
/user request called

And on the browser, you will see the Welcome to GeeksforGeeks.

My Personal Notes

arrow_drop_up