我正在尝试从使用快速应用程序生成器生成的项目中的路由器访问我的应用程序级中间件。
中间件用于使用从路由器接收到的用户 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'));
}
});
最佳答案
如果你这样做
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)
})
}
关于javascript - 如何从路由器访问应用层中间件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58630980/