In Express.js, app.use
is a method used to mount middleware functions in the application's request processing pipeline. Middleware functions are functions that have access to the request object (req
), the response object (res
), and the next middleware function in the application's request-response cycle. They can perform tasks such as modifying the request and response objects, ending the request-response cycle, and calling the next middleware function in the stack.
The basic syntax for app.use
is:
app.use([path,] callback [, callback, ...]);
path
(optional): If a path is specified, the middleware function will only be executed for requests that match that path.callback
: The middleware function to be executed.
Here's an example of using app.use
without a specific path:
const express = require('express');
const app = express();
// Middleware function
app.use((req, res, next) => {
console.log('This middleware will be executed for all requests.');
next();
});
// Route handler
app.get('/', (req, res) => {
res.send('Hello, World!');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
In this example, the middleware function will be executed for all incoming requests because no specific path is specified. If you want to limit the middleware to a specific path, you can provide a path as the first argument to app.use
. For example:
app.use('/api', (req, res, next) => {
console.log('This middleware will be executed for requests to /api/*');
next();
});
In this case, the middleware will only be executed for requests with paths that start with '/api'.