express pass data between middleware
To pass data between middleware in Express, you can use the req
and res
objects. Here are the steps:
Define your middleware function using the
app.use()
method. This function will have access to thereq
,res
, andnext
parameters, representing the request, response, and the next middleware function in the stack.Inside the middleware function, you can store data on the
req
object usingreq.propertyName = value
. This will make the data available to subsequent middleware functions or routes.If you want to pass data to the next middleware function in the stack, you can call
next()
without any arguments. This will continue the execution flow to the next middleware.To access the data passed from the previous middleware, you can use
req.propertyName
in subsequent middleware functions or routes.
Here's an example to illustrate the steps:
const express = require('express');
const app = express();
// Middleware function
const myMiddleware = (req, res, next) => {
req.myData = 'Hello from middleware!';
next();
};
// Route
app.get('/', (req, res) => {
console.log(req.myData); // Output: 'Hello from middleware!'
res.send('Response from route');
});
app.use(myMiddleware);
app.listen(3000, () => {
console.log('Server started on port 3000');
});
In this example, the myMiddleware
function is defined to add the myData
property to the req
object. The route handler then accesses this data using req.myData
.
By following these steps, you can easily pass data between middleware functions in Express.