首页 > 解决方案 > 如何从路由器访问应用级中间件?

问题描述

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

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

我觉得我错过了一些非常简单(或基本)的东西,但无法解决问题(这是我的第一个 Node.js 项目)。所以不仅仅是最佳实践,我正在寻找一个简单的解决方案

我尝试过使用不同的应用程序方法,包括发布。

/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'));
  }
});

标签: javascriptnode.jsexpressmiddleware

解决方案


如果你这样做

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

推荐阅读