我的 app.js 看起来像这样:
app = express();
setup.configure(app);
//...more stuff (e.g. database setup, middleware definition, etc.)...
var api = require('./routes/api');
app.use('/api', api);
module.exports = app;
在 routes/api.js 中,我有这样的带有中间件的路由:
router.get('/myroute',
app.sessionMW,
function (req, res, next) {
//...
});
JSLint 标记错误,因为我将 app
变量声明为全局变量。
如果我用 var
声明它,我会在路由中收到错误,因为应用程序是 undefined
。如果我使用 var app = require('../app')
要求路由文件中的应用程序,我会收到此错误:
Error: Route.get() requires callback functions but got a [object Undefined]
我想通过做正确定义应用程序
var app = express();
但是如何访问路由文件中的应用程序呢?
最佳答案
根据 Express 4.x 文档,您可以使用 req.app
和 res.app
通过请求和响应对象轻松访问应用对象
The Express application object can be referred from the Request object and the Response object as
req.app
, andres.app
, respectively.
- req.app
This property holds a reference to the instance of the Express application that is using the middleware.
- res.app
res.app
is identical to thereq.app
property in the Request object.
代码示例:
server.js:
var path = require('path');
var express = require('express');
var app = express();
app.set('firends', 'nodejs, python');
var page = require(path.join(
__dirname,
'page'
));
app.use('', page);
app.listen(3000);
page.js:
var express = require('express');
var router = express.Router();
router.get('/test-route', function (req, res) {
var app = req.app; // get app object
res.send('firends are: ' + app.get('firends')); // get firends from app
});
module.exports = router;
提示:
- server.js 和 page.js 在同一个文件夹中。
- 使用命令运行:
node server.js
- 访问url:
http://127.0.0.1:3000/test-route
关于javascript - 如何在路由器文件中获取应用程序(在 Node/Express 应用程序中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31317300/