将参数从app.js传递到route.js [英] pass params from app.js to route.js

查看:66
本文介绍了将参数从app.js传递到route.js的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 app.js 和以下代码,还有一个名为router.js的附加文件,用于处理请求的此类post/read/etc

I have app.js with the following code and I've additional file which is called router.js which handle request's such post/read/etc

这是app.js

var express = require('express');
    module.exports = function () {
            var app = express();
             ....
            require('./router/routes')(app, express);
            return app;
        };

router.js如下所示

*/

module.exports = function (app, express) {

    var appRouter = express.Router();
    app.use(appRouter);
    appRouter.route('*')
.post(function (req, res) {

            handler.dispatch(req, res);
        })
        .get(function (req, res) {
            handelr.dispatch(req, res)
        })

有一个很好的方法可以避免传递两个参数(应用程序,表达式)?

There is a nice way to avoid to pass two parameters (app,express) ?

推荐答案

是的,更改文件的结构方式,以便您仅需要app和express.现在,您不再需要将每个模块都包装在一个函数中或传递任何参数.

Yes, change the way you structure your files so you can instead simply require app and express. Now you no longer need to wrap every module in a function or pass any parameters.

app.js

var express = require('express');
var app = express();
module.exports = app;

app.boot = function () {
    // require in middleware, routes, etc, then start listening.
    require('./middleware');
    require('./routes');
    // middleware that comes after routes, such as error handling
    require('./middleware/after'); 
    app.listen();
}
if (require.main === module) {
    //move execution to next tick so we can require app.js in other modules safely
    process.nextTick(app.boot);
}

routes.js

var express = require('express');
var app = require('./app');
var appRouter = express.Router();
app.use(appRouter);
appRouter.route('*');
appRouter.get('/foo', function () {...});
appRouter.post('/foo', function () {...});
module.exports = appRouter; // for unit testing, or you can use this to attach it in app.js instead.


此外,通过将启动功能附加到 app ,您现在可以将该应用程序包含在另一个Express应用程序中,并在需要时将其作为路由器附加,而无需进行任何更改.您所需要做的就是将其插入,附加,然后执行app.boot附加所需的中间件/路由.(对于单元测试很有用)


Additionally, by attaching the boot function to app, you can now include this app into another express app and attach it as a router if needed without having to change anything. All you would have to do is require it in, attach it, and then execute app.boot to attach the needed middleware/routes. (useful for unit testing)

这篇关于将参数从app.js传递到route.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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