Koa.js 路由 koa@router

简介:

Koa.js 的路由


安装:

npm i @koa/router


API参考

基本用法:

const Koa = require('koa');
const Router = require('@koa/router');

const app = new Koa();
const router = new Router();

router.get('/', (ctx, next) => {
 // ctx.router available
});

app
 .use(router.routes())
 .use(router.allowedMethods());



路由方法:

router.get|put|post|patch|delete|del ⇒ Router


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

创建一个路由方法,路由方法指的是HTTP协议的动词,比如Get和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().

匹配到Url路径以后,会执行回调函数,或者控制器的方法。


Additionaly, router.all() can be used to match against all methods.

另外,router.all() 将匹配所有的方法。


router
 .get('/', (ctx, next) => {
  ctx.body = 'Hello World!';
 })
 .post('/users', (ctx, next) => {
  // ...
 })
 .put('/users/:id', (ctx, next) => {
  // ...
 })
 .del('/users/:id', (ctx, next) => {
  // ...
 })
 .all('/users/:id', (ctx, next) => {
  // ...
 });



命名路由:

Named routes

When a route is matched, its path is available at ctx._matchedRoute and if named, the name is available at ctx._matchedRouteName

Route paths will be translated to regular expressions using path-to-regexp.

Query strings will not be considered when matching requests.

Routes can optionally have names. This allows generation of URLs and easy renaming of URLs during development.

router.get('user', '/users/:id', (ctx, next) => {
 // ...
});

router.url('user', 3);
// => "/users/3"



多个中间件:

Multiple middleware

Multiple middleware may be given:


router.get(
 '/users/:id',
 (ctx, next) => {
  return User.findOne(ctx.params.id).then(function(user) {
   ctx.user = user;
   next();
  });
 },
 ctx => {
  console.log(ctx.user);
  // => { id: 17, name: "Alex" }
 }
);



套嵌路由:

Nested routers

Nesting routers is supported:

const forums = new Router();
const posts = new Router();

posts.get('/', (ctx, next) => {...});
posts.get('/:pid', (ctx, 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:

const router = new Router({
 prefix: '/users'
});

router.get('/', ...); // responds to "/users"
router.get('/:id', ...); // responds to "/users/:id"


URL 变量:

URL parameters

Named route parameters are captured and added to ctx.params.


router.get('/:category/:title', (ctx, next) => {
 console.log(ctx.params);
 // => { category: 'programming', title: 'how-to-node' }
});

The path-to-regexp module is used to convert paths to regular expressions.




地址:

https://github.com/koajs/router

修改时间 2021-05-02

真诚赞赏,手留余香
赞赏
随机推荐
Photoshop创建金属质感文字
ffmpeg 拼接视频报错,Found duplicated MOOV Atom. Skipped
Workerman 实现 WebSocket IM 聊天系统 【前端篇】
jQuery Mobile 1.4.5实现类似微信的弹出提示
nginx location 配置返回文本
MySQL 数据库如何存储时间?Datetime 和 Timestamp 之间的抉择
GPS坐标转换经纬度及换算方法
禁止浏览器下拉刷新
自动构建JavaScript
Nginx 代理 Node.js 静态文件比较大无法正常显示,关键词 proxy_temp Permission denied