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

时间:2019-10-30 17:40:33

标签: javascript node.js express middleware

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

中间件用于查询从路由器收到的用户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'));
  }
});

2 个答案:

答案 0 :(得分:2)

如果您这样做的话

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

答案 1 :(得分:0)

您需要致电app.set("MyAppMidW", MyAppMidW),然后才能使用get。或者在app.js文件中执行

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

然后通过路由文件中的req.app.get('MyAppMidW')(req.header('auth-header'))req.app.MyAppMidW(req.header('auth-header'))进行调用。

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