KoaHub平台基于Node.js开发的router路由插件代码

云浩酱_9080

云浩酱_9080

2016-10-19

1572人浏览

原创

KoaHub平台基于Node.js开发的Koa router路由插件代码信息详情
koa-router

Router middleware for koa. Provides RESTful resource routing.

koa-router

Router middleware for koa[list][*]Express-style routing using app.get, app.put, app.post, etc.
[*]Named URL parameters.
[*]Named routes with URL generation.
[*]Responds to OPTIONS requests with allowed methods.
[*]Support for 405 Method Not Allowed and 501 Not Implemented.
[*]Multiple route middleware.
[*]Multiple routers.
[*]Nestable routers.
[*]ES7 async/await support (koa-router 7.x).[/list]koa 2.x

See koa-router 7.x for koa 2.x and async/await support.

Installation

Install using npm:npm install koa-routerAPI Reference[list][*]koa-router
[*]Router ⏏
[*]new Router([opts])
[*]instance
[*].get|put|post|patch|delete ⇒ Router
[*].param(param, middleware) ⇒ Router
[*].use([path], middleware, [...]) ⇒ Router
[*].routes ⇒ function
[*].allowedMethods([options]) ⇒ function
[*].redirect(source, destination, code) ⇒ Router
[*].route(name) ⇒ Layer | false
[*].url(name, params) ⇒ String | Error
[*]static
[*].url(path, params) ⇒ String[/list]Router

Kind: Exported class

new Router([opts])

Create a new router.

[table=50%]

Param TypeDescription [opts] Object [opts.prefix] String prefix router paths

[/table]Example Basic usage:var app = require('koa')();
var router = require('koa-router')();
 
router.get('/', function *(next) {...});
 
app
  .use(router.routes())
  .use(router.allowedMethods());
router.get|put|post|patch|delete ⇒ Router

Create router.verb() methods, where verb is one of the HTTP verbes such as router.get() or router.post().

Match URL patterns to callback functions or controller actions using router.verb(), where verb is one of the HTTP verbs such as router.get() or router.post().router
  .get('/', function *(next) {
    this.body = 'Hello World!';
  })
  .post('/users', function *(next) {
    // ... 
  })
  .put('/users/:id', function *(next) {
    // ... 
  })
  .del('/users/:id', function *(next) {
    // ... 
  });
Route paths will be translated to regular expressions using path-to-regexp.

Query strings will not be considered when matching requests.

Named routes

Routes can optionally have names. This allows generation of URLs and easy renaming of URLs during development.router.get('user', '/users/:id', function *(next) {
 // ... 
});
 
router.url('user', 3);
// => "/users/3" 
Multiple middleware

Multiple middleware may be given:router.get(
  '/users/:id',
  function *(next) {
    this.user = yield User.findOne(this.params.id);
    yield next;
  },
  function *(next) {
    console.log(this.user);
    // => { id: 17, name: "Alex" } 
  }
);
Nested routers

Nesting routers is supported:var forums = new Router();
var posts = new Router();
 
posts.get('/', function *(next) {...});
posts.get('/:pid', function *(next) {...});
forums.use('/forums/:fid/posts', posts.routes(), posts.allowedMethods());
 
// responds to "/forums/123/posts" and "/forums/123/posts/123" 
app.use(forums.routes());
Router prefixes

Route paths can be prefixed at the router level:var router = new Router({
  prefix: '/users'
});
 
router.get('/', ...); // responds to "/users" 
router.get('/:id', ...); // responds to "/users/:id" 
URL parameters

Named route parameters are captured and added to ctx.params.router.get('/:category/:title', function *(next) {
  console.log(this.params);
  // => { category: 'programming', title: 'how-to-node' } 
});
Kind: instance property of Router

[table=50%]

Param Type Description path String [middleware] function route middleware(s) callback function route callback

[/table]router.routes ⇒ function

Returns router middleware which dispatches a route matching the request.

Kind: instance property of Router

router.use([path], middleware, [...]) ⇒ Router

Use given middleware(s) before route callback.

Only runs if any route is matched. If a path is given, the middleware will run for any routes that include that path.

Kind: instance method of Router

[table=50%]

Param Type [path] String middleware function [...] function

[/table]Examplerouter.use(session(), authorize());
 
// use middleware only with given path 
router.use('/users', userAuth());
 
app.use(router.routes());
router.prefix(prefix) ⇒ Router

Set the path prefix for a Router instance that was already initialized.

Kind: instance method of Router

[table=50%]

Param Type prefix String

[/table]Examplerouter.prefix('/things/:thing_id')router.allowedMethods([options]) ⇒ function

Returns separate middleware for responding to OPTIONS requests with an Allow header containing the allowed methods, as well as responding with 405 Method Not Allowed and 501 Not Implemented as appropriate.

Kind: instance method of Router


[table=50%]

Param Type Description [options] Object [options.throw] Boolean throw error instead of setting status and header [options.notImplemented] Function throw the returned value in place of the default NotImplemented error [options.methodNotAllowed] Function throw the returned value in place of the default MethodNotAllowed error

[/table]Examplevar app = koa();
var router = router();
 
app.use(router.routes());
app.use(router.allowedMethods());
 
Example with Boom

var app = koa();
var router = router();
var Boom = require('boom');
 
app.use(router.routes());
app.use(router.allowedMethods({
  throw: true,
  notImplemented: () => new Boom.notImplemented(),
  methodNotAllowed: () => new Boom.methodNotAllowed()
}));
router.redirect(source, destination, code) ⇒ Router

Redirect source to destination URL with optional 30x status code.

Both source and destination can be route names.router.redirect('/login', 'sign-in');This is equivalent to:router.all('/login', function *() {
  this.redirect('/sign-in');
  this.status = 301;
});
Kind: instance method of Router

[table=50%]

Param Type Description source String URL or route name. destination String URL or route name. code Number HTTP status code (default: 301).

[/table]router.route(name) ⇒ Layer | false

Lookup route with given name.

Kind: instance method of Router

Param Type
name String

router.url(name, params) ⇒ String | Error

Generate URL for route. Takes the route name and a map of named

wemall 开源微商城 ,微信商城,商城源码,三级分销,微生鲜,微水果,微外卖,微订餐---专业的o2o系统

wemall地址:http://www.wemallshop.com


代码来源:http://js.koahub.com/home/feature/koa-jwt

相关文章

路由优化大师
路由优化大师

路由优化大师是一款及简单的路由器设置管理软件,其主要功能是一键设置优化路由、屏广告、防蹭网、路由器全面检测及高级设置等,有需要的小伙伴快来保存下载体验吧!

下载

相关标签:

本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

相关专题

更多
GoFrame框架Web开发与路由中间件
GoFrame框架Web开发与路由中间件

本专题聚焦GoFrame框架的Web开发,拆解路由注册与匹配规则、请求参数获取、参数校验与中间件执行顺序,说明统一响应、JWT鉴权、文件上传与接口文档生成的落地方式,并补充优雅重启与测试实践。

2026.11.17

0

15

GoFrame框架安装与gf命令行工具
GoFrame框架安装与gf命令行工具

本专题围绕GoFrame框架的安装与工具链配置展开,讲清Go版本要求、gf命令行的安装方式、代理镜像与依赖准备,说明项目初始化、热编译、交叉编译打包的做法,并整理安装阶段的常见报错与验证步骤。

2026.11.17

0

15

GoFrame框架零基础入门
GoFrame框架零基础入门

本专题整理GoFrame框架的入门知识,从模块化设计理念、环境准备到跑通第一个Web服务,讲清目录分层、配置加载、日志与中间件的用法,并对比Gin、Go-Zero的差异,帮助Go开发者建立整体认知。

2026.11.17

0

15

SQLAlchemy 一对多关系怎么建立
SQLAlchemy 一对多关系怎么建立

SQLAlchemy 一对多关系怎么建立?本专题整理父子表外键、relationship 双向映射、关联查询、级联删除和加载优化等相关文章,帮助你理解并实现常见的 ORM 关系建模。

2026.11.17

0

10

SQLAlchemy 如何增删改查
SQLAlchemy 如何增删改查

SQLAlchemy 如何增删改查?本专题整理 ORM 新增记录、条件查询、更新和删除、Session 事务提交与批量处理等实用文章,帮助你掌握 Python 数据库操作流程。

2026.11.17

0

11

SQLAlchemy ORM 模型怎么写
SQLAlchemy ORM 模型怎么写

SQLAlchemy ORM 模型怎么写?本专题整理模型类定义、Mapped 字段映射、主键与约束、表结构创建和常见报错的相关文章,帮助你从基础配置到实际建模逐步掌握 SQLAlchemy。

2026.11.17

0

16

Go-Zero API开发使用教程
Go-Zero API开发使用教程

本专题聚焦Go-Zero的API开发,拆解.api描述文件的语法结构、路由与分组定义、参数绑定与校验规则,说明统一响应体、JWT鉴权、跨域与接口文档生成的落地方式,并给出网关聚合与接口测试的实践建议。

2026.11.12

160

15

Go-Zero安装与goctl环境配置教程
Go-Zero安装与goctl环境配置教程

本专题围绕Go-Zero的安装与工具链配置展开,讲清Go版本要求、goctl安装方式、代理镜像、protoc依赖与环境变量设置,说明多版本共存、升级回退与CI流水线安装的做法,并整理安装阶段的常见报错与验证步骤。

2026.11.12

120

15

Go-Zero零基础入门教程
Go-Zero零基础入门教程

本专题整理Go-Zero的入门知识,从框架定位、环境准备到跑通第一个API服务,讲清目录分层、配置加载、日志与中间件的基本用法,并对比Gin、Kratos的差异,帮助Go开发者建立整体认知,判断它是否适合当前项目。

2026.11.12

100

15

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程