组织 myapp/routes/* 的正确方法 [英] Proper way to organize myapp/routes/*

查看:25
本文介绍了组织 myapp/routes/* 的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用最新的稳定 node.js 和 npm 中的 express,我创建了我的第一个 express 项目.

Using latest stable node.js and express from npm, I've created my first express project.

默认生成的应用程序定义了 routes/index.js,其中包含一个呈现默认索引视图的路由.

The default generated app defines routes/index.js, which contains a single route that renders the default index view.

我立即假设我可以将其他 .js 文件添加到 routes/文件夹中,并且它们会被包含在内.这没有成功.只包含 routes/index.js .向 routes/index.js 添加额外的路由可以正常工作.

I immediately assumed I could add other .js files to the routes/ folder and they would be included. This didn't pan out. Only routes/index.js is ever included. Adding additional routes to routes/index.js works fine.

按照 express 项目生成器提供的结构,定义和组织 Express 路由的正确方法是什么?

答案,转述 DailyJS 上的文章:

The answer, paraphrasing the article at DailyJS:

给定以下路线:

app.get('/', function() {});
app.get('/users', function() {});
app.get('/users/:id', function() {});

... 创建以下文件:

... Create the following files:

routes/
├── index.js
├── main.js
└── users.js

然后,在 routes/index.js 里面:

Then, inside of routes/index.js:

require('./main');
require('./users');

对于每组新的相关路由,在 routes/中创建一个新文件,并从 routes/index.js 中 require() 它.对不适合其他文件的路由使用 main.js.

推荐答案

我更喜欢动态加载路由,而不是每次添加新路由文件时都必须手动添加另一个需求.这是我目前使用的.

I prefer dynamically loading routes instead of having to manually add another require each time you add a new route file. Here is what I am currently using.

var fs = require('fs');

module.exports = function(app) {
    console.log('Loading routes from: ' + app.settings.routePath);
    fs.readdirSync(app.settings.routePath).forEach(function(file) {
        var route = app.settings.routePath + file.substr(0, file.indexOf('.'));
        console.log('Adding route:' + route);
        require(route)(app);
    });
}

我在应用程序加载时调用它,然后需要 routePath 中的所有文件.每条路线的设置如下:

I call this when the application loads, which then requires all files in the routePath. Each route is setup like the following:

module.exports = function(app) {
    app.get('/', function(req, res) {
        res.render('index', {
            title: 'Express'
        });
    });
}

要添加更多路由,您现在要做的就是在 routePath 目录中添加一个新文件.

To add more routes, all you have to do now is add a new file to the routePath directory.

这篇关于组织 myapp/routes/* 的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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