2way-router 中文文档教程

发布于 6年前 浏览 25 项目主页 更新于 3年前

2way-router

node.js 的路由插件

Usage

Defining routes

var Router = require('2way-router');
var router = new Router();
// you must provide your own controllers
router.route('/')
    .name('main')
    .controller(mainPageController);
router.route('/news')
    .name('news')
    .controller(newsPageController);
router.route('/news/archive/{year ~ /\\d{4}/}-{month ~ /\\d{2}/}-{day ~ /\\d{2}/}/')
    .name('news-archive')
    .controller(newsArchiveController);
router.route('/news/{id:int}')
    .name('news-publication')
    .controller(newsPublicationsController);

Detecting route

router.findRoute('/news/archive/2014-06-21/').done(function (info) {
    var controller = info.route.controller();
    var params = info.params;
});

Creating urls

router.url('news-archive', {
    year: 2014,
    month: '06',
    day: 21,
    page: 3
}).done(function (url) {
    // url === '/news/archive/2014-06-21/?page=3'
});

Full example

您需要运行

npm install 2way-router express promise

示例应用程序:

var Router = require('2way-router');
var Promise = require('promise');
var express = require('express');
var router = new Router();
var links = [
    {
        page: 'main',
        text: 'main page'
    },
    {
        page: 'news',
        text: 'news page'
    },
    {
        page: 'news-archive',
        text: 'news archive for today',
        params: {
            year: new Date().getFullYear(),
            month: pad(new Date().getMonth() + 1, 2),
            day: pad(new Date().getDate(), 2)
        }
    }
];

function pad(value, length) {
    value = String(value);
    while (value.length < length) {
        value = '0' + value;
    }
    return value;
}

function createPage(name, route) {
    function pageController(req, res, params) {
        var pageContent = 'page: ' + name + ', params: <pre>' + JSON.stringify(params.merge(), null, '  ') + '</pre>';
        Promise.all(links.map(function (link) {
            return router.url(link.page, link.params || {});
        })).then(function (urls) {
            pageContent += '<ul>';
            urls.forEach(function (href, index) {
                pageContent += '<li><a href="' + href + '">' + links[index].text + '</a></li>';
            });
            pageContent += '</ul>';
            res.status(200).send(pageContent);
        });
    }

    router.route(route)
        .name(name)
        .controller(pageController);
}

createPage('main', '/');
createPage('news', '/news');
createPage('news-archive', '/news/archive/{year ~ /\\d{4}/}-{month ~ /\\d{2}/}-{day ~ /\\d{2}/}/');
createPage('news-publication', '/news/{id:int}');

var app = express();
app.use(function (req, res) {
    router.findRoute(req.url).then(function (info) {
        info.route.controller()(req, res, info.params);
    }, function () {
        res.status(404).send('Not found');
    });
});
app.listen(8080);

API

Router

router.route(pathTemplate) - 创建新的 Route

router.findRoute(url, [options] ) - 搜索匹配的路由,返回 Promise

router.url(routeName, [params]) - 为名称为 的路由创建 url routeName,返回 Promise

router.registerType(typeConstructor, names) - 注册新的参数类型以在路由中进一步使用,必须在任何 之前调用code>router.route 调用,类型示例可以在 NumberParam.js

Route

route.name([newName])< /code> - 获取/设置路由名称

route.controller([newController]) - 获取/设置路由控制器

route.url([params]) - 为此创建 url route, returns Promise

route.setDefaultParams(params) - 为这个路由设置默认参数

RouteParams

params.getRouteParam( name, [defaultValue=null]) - 获取路由参数值(例如 id in route "/news/{id:int}/"

< code>params.getQueryParam(name, [defaultValue=null]) - 获取具有给定 name 的查询字符串参数(如果存在多个则为最后一个),返回 string

params.getQueryParamValues(name) - 获取具有给定 name 的查询字符串参数的所有值,返回 string[]

2way-router

routing plugin for node.js

Usage

Defining routes

var Router = require('2way-router');
var router = new Router();
// you must provide your own controllers
router.route('/')
    .name('main')
    .controller(mainPageController);
router.route('/news')
    .name('news')
    .controller(newsPageController);
router.route('/news/archive/{year ~ /\\d{4}/}-{month ~ /\\d{2}/}-{day ~ /\\d{2}/}/')
    .name('news-archive')
    .controller(newsArchiveController);
router.route('/news/{id:int}')
    .name('news-publication')
    .controller(newsPublicationsController);

Detecting route

router.findRoute('/news/archive/2014-06-21/').done(function (info) {
    var controller = info.route.controller();
    var params = info.params;
});

Creating urls

router.url('news-archive', {
    year: 2014,
    month: '06',
    day: 21,
    page: 3
}).done(function (url) {
    // url === '/news/archive/2014-06-21/?page=3'
});

Full example

You will need to run

npm install 2way-router express promise

Example application:

var Router = require('2way-router');
var Promise = require('promise');
var express = require('express');
var router = new Router();
var links = [
    {
        page: 'main',
        text: 'main page'
    },
    {
        page: 'news',
        text: 'news page'
    },
    {
        page: 'news-archive',
        text: 'news archive for today',
        params: {
            year: new Date().getFullYear(),
            month: pad(new Date().getMonth() + 1, 2),
            day: pad(new Date().getDate(), 2)
        }
    }
];

function pad(value, length) {
    value = String(value);
    while (value.length < length) {
        value = '0' + value;
    }
    return value;
}

function createPage(name, route) {
    function pageController(req, res, params) {
        var pageContent = 'page: ' + name + ', params: <pre>' + JSON.stringify(params.merge(), null, '  ') + '</pre>';
        Promise.all(links.map(function (link) {
            return router.url(link.page, link.params || {});
        })).then(function (urls) {
            pageContent += '<ul>';
            urls.forEach(function (href, index) {
                pageContent += '<li><a href="' + href + '">' + links[index].text + '</a></li>';
            });
            pageContent += '</ul>';
            res.status(200).send(pageContent);
        });
    }

    router.route(route)
        .name(name)
        .controller(pageController);
}

createPage('main', '/');
createPage('news', '/news');
createPage('news-archive', '/news/archive/{year ~ /\\d{4}/}-{month ~ /\\d{2}/}-{day ~ /\\d{2}/}/');
createPage('news-publication', '/news/{id:int}');

var app = express();
app.use(function (req, res) {
    router.findRoute(req.url).then(function (info) {
        info.route.controller()(req, res, info.params);
    }, function () {
        res.status(404).send('Not found');
    });
});
app.listen(8080);

API

Router

router.route(pathTemplate) - creates new Route

router.findRoute(url, [options]) - searchs for matching route, returns Promise<Route>

router.url(routeName, [params]) - creates url for route with name routeName, returns Promise<string>

router.registerType(typeConstructor, names) - registers new param type for further usage in routes, must be called before any router.route calls, type example can be found at NumberParam.js

Route

route.name([newName]) - get/set route name

route.controller([newController]) - get/set route controller

route.url([params]) - creates url for this route, returns Promise<string>

route.setDefaultParams(params) - set default params for this route

RouteParams

params.getRouteParam(name, [defaultValue=null]) - get route param value (for example id in route "/news/{id:int}/")

params.getQueryParam(name, [defaultValue=null]) - get query string param with given name (last one if many are present), returns string

params.getQueryParamValues(name) - get all values for query string param with given name, returns string[]

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