Passing variables to the next middleware using next() in Express.js
Attach your variable to the res.locals
object, not req
.
Instead of
req.somevariable = variable1;
Have:
res.locals.somevariable = variable1;
As others have pointed out, res.locals
is the recommended way of passing data through middleware.
passing variable to next middleware in req in express.js
That's because the User.findOne
function is asynchronous. The result of that function is only known in the then
block.
const middleware = (req, res, next) => {
User.findOne({ _id: someId })
.then(user => {
req.user = user;
})
.catch(err => { });
next(); // If you put next() here, the request will go straight to the next middleware without waiting for User.findOne() to complete.
};
const middleware = (req, res, next) => {
User.findOne({ _id: someId })
.then(user => {
req.user = user;
next(); // Putting next() here is correct
})
.catch(err => {
next(err); // Remember to handle error to avoid hanging the request
});
};
How to pass a parameter to middleware function in Express JS?
I had the same requirement and this approach works for me.
Middleware file validate.js
exports.grantAccess = function(action, resource){
return async (req, res, next) => {
try {
const permission = roles.can(req.user.role)[action](resource);
// Do something
next();
}
catch (error) {
next(error)
}
}
}
Use of middleware in route file. grantAccess('readAny', 'user')
router.get("/",grantAccess('readAny', 'user'), async (req,res)=>{
// Do something
});
Can I send data via express next() function?
In this case you have a few options (only use one of these!):
- You can just access the req.session.user.username variable from your my_tasks route
- You can use res.locals
- You can add data to the
req
object
In your exports.privateContent function, once a user is found in the database, you can simply add that data to the res.locals:
User.findOne( { 'username': username }, function ( err, obj ) {
if ( true ) {
// this variable will be available directly by the view
res.locals.user = obj;
// this will be added to the request object
req.user = obj;
next();
} else {
res.redirect('/');
}
});
Then in your exports.my_tasks route, res.locals.user
will be whatever obj was in the middleware. You can then simply access that in the view as the variable user
.
So, all together, you can access the data in your route in these ways:
exports.my_tasks = function ( req, res ) {
res.render('tasks/tasks', {
userFromReq: req.user, // this exists because you added in the middleware
userFromSession: req.session.user, // this was already in the session, so you can access
userFromRes: [DO NOT NEED TO DO THIS] // because res.locals are sent straight to the view (Jade).
});
};
Node.js Express How to pass data between middleware?
Demonstrator.find
is an asynchronous function, so you should call next
in its callback like this
exports.list_all_Demonstrator = function(req, res,next) {
//console.log(req.body)
Demonstrator.find({}, function(err, demo) {
if (err){
console.log(err);
}
else {
res.locals.myvar = demo;
}
next(); // <------------
});
};
exports.doSomeStuff = function(req,res,next) {
var data;
data = res.locals.myvar
console.log("Dies ist 2te Funktion:", data);
res.send(data);
}
Otherwise next
will be called before you assign demo
to res.locals.myvar
Express: 4.17: Passing the variable to the next function returns undefined (middleware)
Index file and your controller appear fine once working on your route file.
router.route("/getuser", verifyJWT).get((req, res) => {
console.log(req.app.locals.userId) // <--- Returns undefined
});
Instead of this try to get req...
router.get("/getuser", verifyJWT, (req, res, next) => {
console.log(req.app.locals.userId);
});
How to pass data to next middleware function in NodeJS
Change the route
function inside Router
class as following and the result of socket.write(1)
will be 4:
class Router {
constructor() {
this.middleware = new Middleware
}
route(data) {
each(this.middleware.handlers, function (handler) {
data = handler(data)
})
return data
}
}
Related Topics
Object.Getownpropertynames VS Object.Keys
Date Parsing in JavaScript Is Different Between Safari and Chrome
Solve Cross Origin Resource Sharing with Flask
Jquery .Find() Doesn't Return Data in Ie But Does in Firefox and Chrome
Twitter Bootstrap Alert Message Close and Open Again
JavaScript Return Number of Days,Hours,Minutes,Seconds Between Two Dates
Assign Variable in If Condition Statement, Good Practice or Not
How to Store a Global Value (Not Necessarily a Global Variable) in Jquery
Example of a Circular Reference in JavaScript
How to Call a Parent Method from Child Class in JavaScript
How to Make 'Setinterval' Behave More in Sync, or How to Use 'Settimeout' Instead
How to Convert Dataurl to File Object in JavaScript
How to Split a String into an Array of Characters
How to Serve a File for Download with Angularjs or JavaScript
How to JSON Stringify a JavaScript Date and Preserve Timezone