【问题标题】:routes with multiple files nodejs具有多个文件nodejs的路由
【发布时间】:2012-08-09 05:07:09
【问题描述】:

我想在多个文件中路由

var routes=require('./routes');

在路由/index.js中

exports.inicio=require('./inicio')
exports.home=require('./home')

在 inicio.js 中

exports.index=function(req,res){res.render('index/index',{title: 'Bienvenido a Inmoweb'});}

在 home.js 中

exports.nosotros=function(req, res){res.render('index/nosotros',{title:'Nosotros'});}

当我 console.log(路由)

{
inicio: {index:[function]}, 
home: {nosotros:[function]}
}

所以我在应用程序中调用

app.get('/',routes.inicio.index);

但我想这样打电话

app.get('/',routes.index);
app.get('/nosotros',routes.nosotros);

console.log 应该是????

{
  index:[function], 
  nosotros:[function]
}

怎么做??? tnx 全部

【问题讨论】:

    标签: javascript node.js express


    【解决方案1】:

    您的routes/index.js 可以执行以下操作:

    exports.index = require('./inicio').index
    exports.nosotros = require('./home').nosotros
    

    您可以通过在inico.js 中直接分配给module.exports 来缩短此时间:

    module.exports = function(req,res){res.render('index/index',{title: 'Bienvenido a Inmoweb'});}
    

    现在您可以在routes/index.js 中执行此操作:

    exports.index = require('./inicio') //See the difference? 
    // require('./inicio') now directly exports your route
    exports.nosotros = require('./home').nosotros
    

    明白了吗? :)

    【讨论】:

    • 这不是答案,但我在您的帮助下解决了我的问题,谢谢
    • 安德烈,你的解决方案是什么。如果您提供更多有关如何解决问题的详细信息,将会有所帮助。我觉得rdrey的解法和解释都很好。
    猜你喜欢
    • 1970-01-01
    • 2019-01-24
    • 1970-01-01
    • 1970-01-01
    • 2011-03-31
    • 2017-12-03
    • 1970-01-01
    • 2013-06-01
    • 1970-01-01
    相关资源
    最近更新 更多