如何导出Express中的所有路线?

发布于 2024-11-10 04:55:28 字数 565 浏览 0 评论 0原文

我有一个 NodeJS Express 应用程序,它在一个文件 (app.js) 中变得非常大。

我想将所有路由导出到一个外部文件中,例如 ./lib/routes.js。怎么做呢?

如何导出以下代码并在主 app.js 中正确引用它?

app.get('/logout', function(req, res) {
    res.render('logout', {
        username: req.session.username
    });
});

app.get('/dashboard', function(req, res) {
    res.render('dashboard', {
        username: req.session.username
    });
});

app.get('/login', function(req, res) {
    res.render('login', {
        badLogin: false,
        loginError: false
    });
});

I have an NodeJS Express app that is getting really big in just one file (app.js).

I want to export all my routes into a single, external file, say ./lib/routes.js. How to do that?

How to export the following bit of code and require it correctly in main app.js?

app.get('/logout', function(req, res) {
    res.render('logout', {
        username: req.session.username
    });
});

app.get('/dashboard', function(req, res) {
    res.render('dashboard', {
        username: req.session.username
    });
});

app.get('/login', function(req, res) {
    res.render('login', {
        badLogin: false,
        loginError: false
    });
});

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

雅心素梦 2024-11-17 04:55:28

我所做的就是按控制器对我的路线进行分组。对于每组相关路由(用户、购物车等),我创建一个位于 app/controllers/foo.js 中的控制器文件,其中 foo 是控制器名称。在我的主 javascript 服务器文件(当前所有代码都位于其中)中,我按名称 require 每个控制器,然后调用其 setup 函数,传入我的 Express app 对象,并允许控制器添加它需要的任何路由。

['api', 'authorization', 'users', 'tests'].map(function(controllerName) {
    var controller = require('./controllers/' + controllerName);
    controller.setup(app);
 });

在每个控制器内,我都会执行以下操作:

exports.setup = function(app) {
    app.get('/dashboard', function(req, res) {
        res.render('dashboard', {
            username: req.session.username
        });
    });
};

What I do is group my routes by controller. For each group of related routes (users, shopping cart, whatever), I make a controller file that lives in app/controllers/foo.js where foo is the controller name. In my main javascript server file (where all your code currently lives), I require each controller by name and then call its setup function, passing in my express app object, and allow the controller to add whatever routes it needs.

['api', 'authorization', 'users', 'tests'].map(function(controllerName) {
    var controller = require('./controllers/' + controllerName);
    controller.setup(app);
 });

Inside each controller, I do something like:

exports.setup = function(app) {
    app.get('/dashboard', function(req, res) {
        res.render('dashboard', {
            username: req.session.username
        });
    });
};
满地尘埃落定 2024-11-17 04:55:28

为什么不做这样的事情:

// logout.js
module.exports = function(req, res){
  res.render('logout', {
    username: req.session.username
  });
});

// dashboard.js
module.exports = function(req, res){
  res.render('dashboard', {
    username: req.session.username
  });
});

// login.js
module.exports = function(req, res){
  res.render('login', {
    badLogin: false,
    loginError: false
  });
});

// app.js
app.get('/logout', require('logout'));
app.get('/dashboard', require('dashboard'));
app.get('/login', require('login'));

另外,您可以轻松想象使用 http://nodejs。 org/docs/v0.4.8/api/fs.html#fs.readdir 循环遍历routes目录并以编程方式加载它们。

你甚至可以做一些类似的事情......

module.exports.handler[] = {
    method : 'get',
    route  : '/login',
    action : res.render('login', {
       badLogin: false,
       loginError: false
    });
}

尽管我想我会花一点时间思考如何简化它。

Why not do something like this:

// logout.js
module.exports = function(req, res){
  res.render('logout', {
    username: req.session.username
  });
});

// dashboard.js
module.exports = function(req, res){
  res.render('dashboard', {
    username: req.session.username
  });
});

// login.js
module.exports = function(req, res){
  res.render('login', {
    badLogin: false,
    loginError: false
  });
});

// app.js
app.get('/logout', require('logout'));
app.get('/dashboard', require('dashboard'));
app.get('/login', require('login'));

Also, you could imagine easily using http://nodejs.org/docs/v0.4.8/api/fs.html#fs.readdir to loop through a routes directory and load these up programmatically.

You could even do something along the lines of...

module.exports.handler[] = {
    method : 'get',
    route  : '/login',
    action : res.render('login', {
       badLogin: false,
       loginError: false
    });
}

Though I think I'd spend a little time thinking about how to simplify that.

请爱~陌生人 2024-11-17 04:55:28

使用 glob 您可以导出目录中的所有路由,例如“/routes”:

npm i --保存 glob


    // *** /routes/index.js file ***

    const express = require('express')
    const Router = express.Router
    const router = Router()
    const glob = require('glob')


    /**
     * options ignore files inside routes folder
     */
    const options = {
        ignore: [`${__dirname}/_helpers.js`, `${__dirname}/index.js`]
    }

    /**
     * read all files on current directory and export routes as lowercase of the filename
     * example 'routes/Products.js' route will be access by '/products'
     */
    const routes = 
        glob.sync(__dirname + '/*.js', options)
            .map(filename => {
                const arr = filename.split('/')
                let name = arr.pop();
                name = name.replace('.js', '')
                return {
                    path: `/${name.toLowerCase()}`,
                    router: require(`${filename.replace('.js', '')}`)
                }
            })
            .filter(obj => Object.getPrototypeOf(obj.router) == Router)
            .forEach(obj => router.use(obj.path, obj.router))


    module.exports = router;

然后

保存 glob

在 app.js 上

// app.js file

const express = require('express')
const routes = require('./routes')


const app = express()

app.use('/api', routes)

using glob you can export all routes on directory for example '/routes':

npm i --save glob


    // *** /routes/index.js file ***

    const express = require('express')
    const Router = express.Router
    const router = Router()
    const glob = require('glob')


    /**
     * options ignore files inside routes folder
     */
    const options = {
        ignore: [`${__dirname}/_helpers.js`, `${__dirname}/index.js`]
    }

    /**
     * read all files on current directory and export routes as lowercase of the filename
     * example 'routes/Products.js' route will be access by '/products'
     */
    const routes = 
        glob.sync(__dirname + '/*.js', options)
            .map(filename => {
                const arr = filename.split('/')
                let name = arr.pop();
                name = name.replace('.js', '')
                return {
                    path: `/${name.toLowerCase()}`,
                    router: require(`${filename.replace('.js', '')}`)
                }
            })
            .filter(obj => Object.getPrototypeOf(obj.router) == Router)
            .forEach(obj => router.use(obj.path, obj.router))


    module.exports = router;

then

on app.js

// app.js file

const express = require('express')
const routes = require('./routes')


const app = express()

app.use('/api', routes)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文