【发布时间】:2013-12-16 20:25:46
【问题描述】:
我在需要 Express.js 中间件时遇到问题;我有app.'s中的代码:
...
var middlewares = require('./middlewares');
...
routes = require('./routes')(app, config, crypto, middlewares, models, oauth2);
...
这需要./middlewares/index.js:
/*jslint es5: true, indent: 2, node:true, nomen: true, maxlen: 80, vars: true*/
'use strict';
var middlewares = function (app, config, models, oauth2) {
var that = {};
that.touch = require('./touch.js')(app, config, models, oauth2);
return that;
};
module.exports = middlewares;
这反过来(上面是简化的,但也包含需要其他中间件)需要./middlewares/touch.js:
/*jslint es5: true, indent: 2, node: true, nomen: true, maxlen: 80, vars: true*/
'use strict';
var touch = function (app, config, models, oauth2) {
return function (req, res, next) {
console.log('Touch');
next();
};
};
module.exports = touch;
并从./routes/index.js调用它:
/*jslint es5: true, indent: 2, node:true, nomen: true, maxlen: 80, vars: true*/
'use strict';
var routes = function (app, config, crypto, middlewares, models, oauth2) {
var that = {};
app.get(
'/',
middlewares.touch(app, config, models, oauth2),
function (req, res) {
res.send('Hello world!');
}
);
that.auth = require('./auth')(app, config, crypto, models, oauth2);
return that;
};
module.exports = routes;
虽然当我这样做时,我得到了错误:
TypeError: Object function (app, config, models, oauth2) {
var that = {};
that.touch = require('./touch.js')(app, config, models, oauth2);
return that;
} has no method 'touch'
当我需要来自app.js 的./middlewares/touch.js 时,例如:
...
var touch = require('./middlewares/touch.js');
...
routes = require('./routes')(app, config, crypto, touch, models, oauth2);
...
在./routes/index.js 我这样称呼它:
/*jslint es5: true, indent: 2, node:true, nomen: true, maxlen: 80, vars: true*/
'use strict';
var routes = function (app, config, crypto, touch, models, oauth2) {
var that = {};
app.get(
'/',
touch(app, config, models, oauth2),
function (req, res) {
res.send('Hello world!');
}
);
that.auth = require('./auth')(app, config, crypto, models, oauth2);
return that;
};
module.exports = routes;
我没有错误!一定是我通过./middlewares/index.js 引用它的方式,但我可以终生解决它吗?
任何想法堆栈溢出?
编辑:
好的,那么问题仍然存在;
- 我想从内部
require./middlewares/index.jsapp.js -
./middlewares/index.js需要我所有的中间件,例如./touch.js - 我只需要将
middlewares对象传递给其他模块即可访问其方法,例如middlewares可以传递到我的routes模块中,我可以引用触摸中间件,例如middlewares.touch()
非常简单;我希望 require 我所有的中间件并将它们传递到路由模块中,例如:
...
var middlewares = require('./middlewares');
...
routes = require('./routes')(app, middlewares);
...
并在如下路径中使用我的中间件:
/*jslint es5: true, indent: 2, node:true, nomen: true, maxlen: 80, vars: true*/
'use strict';
var routes = function (app, middlewares) {
var that = {};
app.get(
'/',
middlewares.touch,
function (req, res) {
res.send('Hello world!');
}
);
that.auth = require('./auth')(app);
return that;
};
module.exports = routes;
我应该怎么做?看看这个问题的顶部,看看我现在是如何尝试(和失败)的,感谢大家的帮助!
此外,应该模块return 的东西,例如; routes 模块真的不需要返回任何东西,或者应该/应该吗?
【问题讨论】:
标签: node.js methods express middleware