Express:如何将应用程序实例传递给来自不同文件的路由? [英] Express: How to pass app-instance to routes from a different file?
问题描述
我想将我的路由分成不同的文件,其中一个文件包含所有路由,另一个文件包含相应的操作.我目前有一个解决方案来实现这一点,但是我需要使应用程序实例全局化才能在操作中访问它.我当前的设置如下所示:
I want to split up my routes into different files, where one file contains all routes and the other one the corresponding actions. I currently have a solution to achieve this, however I need to make the app-instance global to be able to access it in the actions. My current setup looks like this:
app.js:
var express = require('express');
var app = express.createServer();
var routes = require('./routes');
var controllers = require('./controllers');
routes.setup(app, controllers);
app.listen(3000, function() {
console.log('Application is listening on port 3000');
});
routes.js:
exports.setup = function(app, controllers) {
app.get('/', controllers.index);
app.get('/posts', controllers.posts.index);
app.get('/posts/:post', controllers.posts.show);
// etc.
};
控制器/index.js:
controllers/index.js:
exports.posts = require('./posts');
exports.index = function(req, res) {
// code
};
控制器/posts.js:
controllers/posts.js:
exports.index = function(req, res) {
// code
};
exports.show = function(req, res) {
// code
};
然而,这个设置有一个大问题:我有一个数据库和一个应用程序实例,我需要传递给操作 (controllers/*.js).我能想到的唯一选择是将两个变量设为全局,这并不是真正的解决方案.我想将路由与操作分开,因为我有很多路由并且希望它们位于一个中心位置.
However, this setup has a big issue: I have a database- and an app-instance I need to pass to the actions (controllers/*.js). The only option I could think of, is making both variables global which isn't really a solution. I want to separate routes from the actions because I have a lot of routes and want them in a central place.
将变量传递给操作但将操作与路由分开的最佳方法是什么?
What's the best way to pass variables to the actions but separate the actions from the routes?
推荐答案
使用 req.app
, req.app.get('somekey')
在请求和响应对象上设置通过调用 express()
创建的应用程序变量.
The application variable created by calling express()
is set on the request and response objects.
这篇关于Express:如何将应用程序实例传递给来自不同文件的路由?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!