问题
project demo structure
- middleware
- auth.js
- routes
- user.js
- controllers
- userController.js
auth.js
exports.authUser=(req,res,next)=>{
...
//got user value somehow and it's fine
req.user=user;
return next();
}
user.js (route)
server.get("/users",authUser,userController.userList);
}
userController.js (Controller)
exports.userList=(req,res,next)=>{
console.log(req.user);
...
}
log output is undefined
What is the actual way of passing value in restify?
- tried restify.plugins.pre.context way too.
- tried passing value in next function.
- tried putting fucntions on [ ] as in
server.get("/users",[authUser,userController.userList]);
回答1:
When you add data
to the req.data
for example and if the data you add is retrieved from a database or from another service that might take time, then make sure you add the next()
in the condition when the data has been received or an error.
📝 For an example of a middleware:
const myCustomMiddleware = (req, res, next) => {
UserModel.find ('...')
.then(data => {
// set req.data
req.data = data;
// next for set req.data
next();
}).catch(ex => {
// next for error
next();
});
// dont add the next function outside the `then and catch`,
// next(); well make req.data 'undefined'
}
🌏 For example in sandbox with timeout: https://codesandbox.io/s/heuristic-glitter-3yq4z
I hope it can help.
回答2:
user.js (route)
server.get("/users",authUser,function (req, res) {
userController.userList(req, function (result) {
res.send(result)
})
})
userController.js (Controller)
exports.userList=(req,callback)=>{
console.log(req.user);
callback(null)
}
来源:https://stackoverflow.com/questions/59601918/passing-value-from-middleware-to-controller-in-restify-using-req-data-is-not-wor