如何从路由器访问应用级中间件?

How to access application-level middleware from router?

我正在尝试从使用 express 应用程序生成器生成的项目中的路由器访问我的应用程序级中间件。

中间件用于使用从路由器收到的用户 ID 查询数据库。

我觉得我遗漏了一些非常简单(或基本)但无法解决的问题(这是我的第一个 Node.js 项目)。因此,除了最佳实践之外,我还在寻找一个简单的解决方案

我尝试过使用不同的应用方法,包括 post。

/app.js

var MyAppMidW = function (req, res, next) {
  res.send(queryDB(req));
  next()
}
app.use(MyAppMidW);

/routes/index.js

router.get("/dbquery", (req, res) => {
  if (req.header('auth-header')) {
    res.send(req.app.get.MyAppMidW(req.header('auth-header'))); //The problem
  }
  else {
    res.send(req.app.get('defaultData')); //This works
  }
});

错误消息包括“$middleware 不是函数”和“$middleware 未定义”。

解决方案

/app.js

app.MyAppMidW = function (req) {
  queryDB(req);
}

/routes/index.js

router.get("/dbquery", (req, res) => {
  if (req.header('auth-header')) {
    req.app.MyAppMidW(req.header('auth-header'))); //Makes a database query
    res.send(req.app.get('defaultData')); //Fetches database query result
  }
  else {
    res.send(req.app.get('defaultData'));
  }
});

你需要调用app.set("MyAppMidW", MyAppMidW)然后你就可以使用get了。或者在 app.js 文件

中执行此操作
app.MyAppMidW = function (req, res, next) {
  res.send(queryDB(req));
  next()
}

然后在routes文件中通过req.app.get('MyAppMidW')(req.header('auth-header'))req.app.MyAppMidW(req.header('auth-header'))调用

但是当您说 app.use(MyAppMidW) 时,中间件会自动调用,默认情况下每个请求都会调用该函数。因此无需在路由器函数中显式调用它。

如果你这样做

     app.use(MyAppMidW);

每个请求都会查询您的数据库,这不是您想要的。我猜你使用的是 MVC 设计模式。

在你的路线文件夹中你有这样的东西:

  import appController from "../controllers/app.js"
  router.get("/dbquery", appController.MyAppQuery)

在你的 controllers 文件夹中你有查询数据库的逻辑

  exports.MyAppQuery = (req, res){
     //If u use mongodb for example
    YourModel.find().then(data => {
       res.json(data)
    })
  }