如何动态更改所有节点/快速路由的前缀

时间:2018-09-06 05:47:01

标签: javascript node.js express

Hiii,我正在从事nodejs express项目,我想动态添加路由前缀。有谁知道一种配置express的方法来在所有路由之前动态更改前缀?例如,目前我有:

localhost:8000/default/example/page

我想在单击另一个仪表板链接时将默认值更改为基本根目录中的v1。

localhost:8000/v1/example/page 

我正在使用autoloader.js文件加载所有路由。

'use strict';

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var fs = require('fs');

var Autoloader = function () {
    function Autoloader() {
        _classCallCheck(this, Autoloader);

        this.routes = [];
        this.path = __dirname;
    }

    _createClass(Autoloader, [{
        key: 'initRoutes',
        value: function initRoutes() {
            var routes = [];
            // get routes names
            fs.readdirSync(this.path).forEach(function (name) {
                if (name !== 'autoloader.js') {
                    routes.push(name.split('.')[0]);
                }
            });

            this.routes = routes;
        }
    }, {
        key: 'allRoutesNames',
        value: function allRoutesNames() {
            this.initRoutes();

            var routes = [];

            this.routes.forEach(function (name) {
                routes.push('/' + name + '*');
            });

            return routes;
            console.log(routes);
        }
    }, {
        key: 'loadRoutes',
        value: function loadRoutes(expressApp, options) {
            // If verbose
            var verbose = options.verbose;

            this.routes.forEach(function (name) {
                // Log module
                verbose && console.log('\n   %s:', name);

                var obj = require('./' + name);
                var name = obj.name || name;
                var prefix = obj.prefix || '';
                var engine = obj.engine || 'handlebars';
                var before = obj.before || false;
                var method;
                var path;
                var routeName;
                var prefixs = '/default'+ prefix; // want to add v1 dynamically at the place of default
                // generate routes based
                // on the exported methods
                for (var key in obj) {
                    // "reserved" exports
                    if (~['name', 'prefix', 'engine', 'before'].indexOf(key)) continue;
                    // route exports
                    switch (key) {
                        case 'list':
                            method = 'get';
                            path = '/' + name + 's';
                            break;
                        case 'show':
                            method = 'get';
                            path = '/' + name + '/:_id';
                            break;
                        case 'new':
                            method = 'get';
                            path = '/' + name + '/new';
                            break;
                        case 'create':
                            method = 'post';
                            path = '/' + name;
                            break;
                        case 'edit':
                            method = 'get';
                            path = '/' + name + '/:_id/edit';
                            break;
                        case 'update':
                            method = 'put';
                            path = '/' + name + '/:_id';
                            break;
                        case 'remove':
                            method = 'get';
                            path = '/' + name + '/:_id/remove';
                            break;
                        case 'delete':
                            method = 'delete';
                            path = '/' + name + '/:_id';
                            break;
                        case 'index':
                            method = 'get';
                            path = prefix === '' ? '/' : '';
                            break;
                        default:
                            method = 'get';
                            path = '/' + key;
                    }

                    path = prefixs + path;
                    routeName = name + '.' + key;
                    if (before) {
                        expressApp[method](path, routeName, before, obj[key]);
                        verbose && console.log('     %s %s -> before -> %s', method.toUpperCase(), path, routeName);
                    } else {
                        expressApp[method](path, routeName, obj[key]);
                        verbose && console.log('     %s %s -> %s', method.toUpperCase(), path, routeName);
                    }
                }
            });
        }
    }]);
    console.log(Autoloader);
    return Autoloader;
}();
module.exports = Autoloader;

仪表板路线文件

exports.prefix = '/dashboard';

//exports.before = function(request, response, next) { next() };

exports.example1 = function(request, response) {
    response.render('dashboard/example1', {
        title: 'example1'
    });
};
exports.example2 = function(request, response) {
    response.render('dashboard/example2', {
        title: 'example2'
    });
};
exports.example3 = function(request, response) {
    response.render('dashboard/example3', {
        title: 'example3'
    });
};
exports.example4 = function(request, response) {
    response.render('dashboard/example4', {
        title: 'example4'
    });
};
exports.example5 = function(request, response) {
    response.render('dashboard/example5', {
        title: 'example5'
    });
};

0 个答案:

没有答案