项目演示结构
- 中间件
- auth.js
- 路线
- 用户.js
- Controller
- userController.js
auth.js
exports.authUser=(req,res,next)=>{
...
//got user value somehow and it's fine
req.user=user;
return next();
}
user.js(路由)
server.get("/users",authUser,userController.userList);
}
userController.js( Controller )
exports.userList=(req,res,next)=>{
console.log(req.user);
...
}
日志输出未定义
restify 中传递值的实际方式是什么?
- 也尝试过restify.plugins.pre.context方式。
- 尝试在下一个函数中传递值。
- 尝试在 [ ] 上添加函数
server.get("/users",[authUser,userController.userList]);
最佳答案
例如,当您将数据
添加到req.data
时,如果您添加的数据是从数据库或其他可能需要时间的服务检索的,然后确保在收到数据或出现错误时的条件中添加next()
。
📝 中间件示例:
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'
}
🌏 例如在有超时的沙盒中:https://codesandbox.io/s/heuristic-glitter-3yq4z
希望对你有帮助。
关于javascript - 使用 req.data 将值从中间件传递到 Restify 中的 Controller 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59601918/