Express:如何将应用程序实例传递给来自不同文件的路由? [英] Express: How to pass app-instance to routes from a different file?

查看:19
本文介绍了Express:如何将应用程序实例传递给来自不同文件的路由?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将我的路由分成不同的文件,其中一个文件包含所有路由,另一个文件包含相应的操作.我目前有一个解决方案来实现这一点,但是我需要使应用程序实例全局化才能在操作中访问它.我当前的设置如下所示:

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.

参见:https://github.com/visionmedia/express/blob/76147c78a15904d4e4e469095a29d1bec9775ab6/lib/express.js#L34-L35

这篇关于Express:如何将应用程序实例传递给来自不同文件的路由?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆