使用 req.data 将值从中间件传递到控制器 restify 不起作用?

passing value from middleware to controller in restify using req.data is not working?

项目演示结构

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(控制器)

exports.userList=(req,res,next)=>{
console.log(req.user);
...
}

日志输出为undefined

在 restify 中传递值的实际方式是什么?

server.get("/users",[authUser,userController.userList]);

例如,当您将 data 添加到 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

希望能帮到你

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)
}