javascript - 如何从路由器访问应用级中间件?
问题描述
我正在尝试在使用快速应用程序生成器生成的项目中从路由器访问我的应用程序级中间件。
中间件用于使用从路由器接收到的用户 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)
})
}
推荐阅读
- r - 基于其他列在 R 中添加新列
- reactjs - 在 React SSR 的组件之外检索 url 参数
- android - Google Play 控制台无用的错误消息
- python - 发生异常:ImportError DLL load failed while importing pdftotext: The specified module could not be found
- python - 比较两个系列(pandas 或 numpy)中的功能,包括通配符
- c# - 查找用户网络的网关
- ios - 在 Objective-C 中分配 UIColor 标准颜色
- performance - 如何在 Visual Studio 2017 C++ 项目中启用应用程序时间线?
- javascript - 如何遍历 Javascript 中的嵌套对象?
- postgresql - 如何在 Openshift 3 上使用端口转发数据库 Postgrsql 进行连接