UNPKG

12.1 kBMarkdownView Raw
1# koa-router
2
3[![NPM version](http://img.shields.io/npm/v/koa-router.svg?style=flat)](https://npmjs.org/package/koa-router) [![NPM Downloads](https://img.shields.io/npm/dm/koa-router.svg?style=flat)](https://npmjs.org/package/koa-router) [![Node.js Version](https://img.shields.io/node/v/koa-router.svg?style=flat)](http://nodejs.org/download/) [![Build Status](http://img.shields.io/travis/alexmingoia/koa-router.svg?style=flat)](http://travis-ci.org/alexmingoia/koa-router) [![Tips](https://img.shields.io/gratipay/alexmingoia.svg?style=flat)](https://www.gratipay.com/alexmingoia/) [![Gitter Chat](https://img.shields.io/badge/gitter-join%20chat-1dce73.svg?style=flat)](https://gitter.im/alexmingoia/koa-router/)
4
5> Router middleware for [koa](https://github.com/koajs/koa)
6
7* Express-style routing using `app.get`, `app.put`, `app.post`, etc.
8* Named URL parameters.
9* Named routes with URL generation.
10* Responds to `OPTIONS` requests with allowed methods.
11* Support for `405 Method Not Allowed` and `501 Not Implemented`.
12* Multiple route middleware.
13* Multiple routers.
14* Nestable routers.
15* ES7 async/await support.
16
17## Migrating to 7 / Koa 2
18
19- The API has changed to match the new promise-based middleware
20 signature of koa 2. See the
21 [koa 2.x readme](https://github.com/koajs/koa/tree/2.0.0-alpha.3) for more
22 information.
23- Middleware is now always run in the order declared by `.use()` (or `.get()`,
24 etc.), which matches Express 4 API.
25
26## Installation
27
28Install using [npm](https://www.npmjs.org/):
29
30```sh
31npm install koa-router
32```
33
34## API Reference
35
36* [koa-router](#module_koa-router)
37 * [Router](#exp_module_koa-router--Router) ⏏
38 * [new Router([opts])](#new_module_koa-router--Router_new)
39 * _instance_
40 * [.get|put|post|patch|delete](#module_koa-router--Router+get|put|post|patch|delete) ⇒ <code>Router</code>
41 * [.routes](#module_koa-router--Router+routes) ⇒ <code>function</code>
42 * [.use([path], middleware, [...])](#module_koa-router--Router+use) ⇒ <code>Router</code>
43 * [.prefix(prefix)](#module_koa-router--Router+prefix) ⇒ <code>Router</code>
44 * [.allowedMethods([options])](#module_koa-router--Router+allowedMethods) ⇒ <code>function</code>
45 * [.redirect(source, destination, code)](#module_koa-router--Router+redirect) ⇒ <code>Router</code>
46 * [.route(name)](#module_koa-router--Router+route) ⇒ <code>Layer</code> &#124; <code>false</code>
47 * [.url(name, params)](#module_koa-router--Router+url) ⇒ <code>String</code> &#124; <code>Error</code>
48 * [.param(param, middleware)](#module_koa-router--Router+param) ⇒ <code>Router</code>
49 * _static_
50 * [.url(path, params)](#module_koa-router--Router.url) ⇒ <code>String</code>
51
52<a name="exp_module_koa-router--Router"></a>
53### Router ⏏
54**Kind**: Exported class
55<a name="new_module_koa-router--Router_new"></a>
56#### new Router([opts])
57Create a new router.
58
59
60| Param | Type | Description |
61| --- | --- | --- |
62| [opts] | <code>Object</code> | |
63| [opts.prefix] | <code>String</code> | prefix router paths |
64
65**Example**
66Basic usage:
67
68```javascript
69var app = require('koa')();
70var router = require('koa-router')();
71
72router.get('/', function (ctx, next) {...});
73
74app
75 .use(router.routes())
76 .use(router.allowedMethods());
77```
78<a name="module_koa-router--Router+get|put|post|patch|delete"></a>
79#### router.get|put|post|patch|delete ⇒ <code>Router</code>
80Create `router.verb()` methods, where *verb* is one of the HTTP verbes such
81as `router.get()` or `router.post()`.
82
83Match URL patterns to callback functions or controller actions using `router.verb()`,
84where **verb** is one of the HTTP verbs such as `router.get()` or `router.post()`.
85
86```javascript
87router
88 .get('/', function (ctx, next) {
89 ctx.body = 'Hello World!';
90 })
91 .post('/users', function (ctx, next) {
92 // ...
93 })
94 .put('/users/:id', function (ctx, next) {
95 // ...
96 })
97 .del('/users/:id', function (ctx, next) {
98 // ...
99 });
100```
101
102Route paths will be translated to regular expressions used to match requests.
103
104Query strings will not be considered when matching requests.
105
106#### Named routes
107
108Routes can optionally have names. This allows generation of URLs and easy
109renaming of URLs during development.
110
111```javascript
112router.get('user', '/users/:id', function (ctx, next) {
113 // ...
114});
115
116router.url('user', 3);
117// => "/users/3"
118```
119
120#### Multiple middleware
121
122Multiple middleware may be given:
123
124```javascript
125router.get(
126 '/users/:id',
127 function (ctx, next) {
128 return User.findOne(ctx.params.id).then(function(user) {
129 ctx.user = user;
130 next();
131 });
132 },
133 function (ctx) {
134 console.log(ctx.user);
135 // => { id: 17, name: "Alex" }
136 }
137);
138```
139
140### Nested routers
141
142Nesting routers is supported:
143
144```javascript
145var forums = new Router();
146var posts = new Router();
147
148posts.get('/', function *(ctx, next) {...});
149posts.get('/:pid', function *(ctx, next) {...});
150forums.use('/forums/:fid/posts', posts.routes(), posts.allowedMethods());
151
152// responds to "/forums/123/posts" and "/forums/123/posts/123"
153app.use(forums.routes());
154```
155
156#### Router prefixes
157
158Route paths can be prefixed at the router level:
159
160```javascript
161var router = new Router({
162 prefix: '/users'
163});
164
165router.get('/', ...); // responds to "/users"
166router.get('/:id', ...); // responds to "/users/:id"
167```
168
169#### URL parameters
170
171Named route parameters are captured and added to `ctx.params`.
172
173```javascript
174router.get('/:category/:title', function (ctx, next) {
175 console.log(ctx.params);
176 // => { category: 'programming', title: 'how-to-node' }
177});
178```
179
180The [path-to-regexp](https://github.com/pillarjs/path-to-regexp) module is used
181to convert paths to regular expressions.
182
183**Kind**: instance property of <code>[Router](#exp_module_koa-router--Router)</code>
184
185| Param | Type | Description |
186| --- | --- | --- |
187| path | <code>String</code> | |
188| [middleware] | <code>function</code> | route middleware(s) |
189| callback | <code>function</code> | route callback |
190
191<a name="module_koa-router--Router+routes"></a>
192#### router.routes ⇒ <code>function</code>
193Returns router middleware which dispatches a route matching the request.
194
195**Kind**: instance property of <code>[Router](#exp_module_koa-router--Router)</code>
196<a name="module_koa-router--Router+use"></a>
197#### router.use([path], middleware, [...]) ⇒ <code>Router</code>
198Use given middleware.
199
200Middleware run in the order they are defined by `.use()`. They are invoked
201sequentially, requests start at the first middleware and work their way
202"down" the middleware stack.
203
204**Kind**: instance method of <code>[Router](#exp_module_koa-router--Router)</code>
205
206| Param | Type |
207| --- | --- |
208| [path] | <code>String</code> |
209| middleware | <code>function</code> |
210| [...] | <code>function</code> |
211
212**Example**
213```javascript
214// session middleware will run before authorize
215router
216 .use(session())
217 .use(authorize());
218
219// use middleware only with given path
220router.use('/users', userAuth());
221
222// or with an array of paths
223router.use(['/users', '/admin'], userAuth());
224
225app.use(router.routes());
226```
227<a name="module_koa-router--Router+prefix"></a>
228#### router.prefix(prefix) ⇒ <code>Router</code>
229Set the path prefix for a Router instance that was already initialized.
230
231**Kind**: instance method of <code>[Router](#exp_module_koa-router--Router)</code>
232
233| Param | Type |
234| --- | --- |
235| prefix | <code>String</code> |
236
237**Example**
238```javascript
239router.prefix('/things/:thing_id')
240```
241<a name="module_koa-router--Router+allowedMethods"></a>
242#### router.allowedMethods([options]) ⇒ <code>function</code>
243Returns separate middleware for responding to `OPTIONS` requests with
244an `Allow` header containing the allowed methods, as well as responding
245with `405 Method Not Allowed` and `501 Not Implemented` as appropriate.
246
247**Kind**: instance method of <code>[Router](#exp_module_koa-router--Router)</code>
248
249| Param | Type | Description |
250| --- | --- | --- |
251| [options] | <code>Object</code> | |
252| [options.throw] | <code>Boolean</code> | throw error instead of setting status and header |
253| [options.notImplemented] | <code>Function</code> | throw throw the returned value in place of the default NotImplemented error |
254| [options.methodNotAllowed] | <code>Function</code> | throw the returned value in place of the default MethodNotAllowed error |
255
256**Example**
257```javascript
258var app = koa();
259var router = router();
260
261app.use(router.routes());
262app.use(router.allowedMethods());
263
264```
265**Example with [Boom](https://github.com/hapijs/boom)**
266```javascript
267var app = koa();
268var router = router();
269var Boom = require('boom');
270
271app.use(router.routes());
272app.use(router.allowedMethods({
273 throw: true,
274 notImplemented: () => new Boom.notImplemented(),
275 methodNotAllowed: () => new Boom.methodNotAllowed()
276}));
277```
278<a name="module_koa-router--Router+redirect"></a>
279#### router.redirect(source, destination, code) ⇒ <code>Router</code>
280Redirect `source` to `destination` URL with optional 30x status `code`.
281
282Both `source` and `destination` can be route names.
283
284```javascript
285router.redirect('/login', 'sign-in');
286```
287
288This is equivalent to:
289
290```javascript
291router.all('/login', function (ctx) {
292 ctx.redirect('/sign-in');
293 ctx.status = 301;
294});
295```
296
297**Kind**: instance method of <code>[Router](#exp_module_koa-router--Router)</code>
298
299| Param | Type | Description |
300| --- | --- | --- |
301| source | <code>String</code> | URL or route name. |
302| destination | <code>String</code> | URL or route name. |
303| code | <code>Number</code> | HTTP status code (default: 301). |
304
305<a name="module_koa-router--Router+route"></a>
306#### router.route(name) ⇒ <code>Layer</code> &#124; <code>false</code>
307Lookup route with given `name`.
308
309**Kind**: instance method of <code>[Router](#exp_module_koa-router--Router)</code>
310
311| Param | Type |
312| --- | --- |
313| name | <code>String</code> |
314
315<a name="module_koa-router--Router+url"></a>
316#### router.url(name, params) ⇒ <code>String</code> &#124; <code>Error</code>
317Generate URL for route. Takes either map of named `params` or series of
318arguments (for regular expression routes).
319
320```javascript
321router.get('user', '/users/:id', function (ctx, next) {
322 // ...
323});
324
325router.url('user', 3);
326// => "/users/3"
327
328router.url('user', { id: 3 });
329// => "/users/3"
330```
331
332**Kind**: instance method of <code>[Router](#exp_module_koa-router--Router)</code>
333
334| Param | Type | Description |
335| --- | --- | --- |
336| name | <code>String</code> | route name |
337| params | <code>Object</code> | url parameters |
338
339<a name="module_koa-router--Router+param"></a>
340#### router.param(param, middleware) ⇒ <code>Router</code>
341Run middleware for named route parameters. Useful for auto-loading or
342validation.
343
344**Kind**: instance method of <code>[Router](#exp_module_koa-router--Router)</code>
345
346| Param | Type |
347| --- | --- |
348| param | <code>String</code> |
349| middleware | <code>function</code> |
350
351**Example**
352```javascript
353router
354 .param('user', function (id, ctx, next) {
355 ctx.user = users[id];
356 if (!ctx.user) return ctx.status = 404;
357 return next();
358 })
359 .get('/users/:user', function (ctx) {
360 ctx.body = ctx.user;
361 })
362 .get('/users/:user/friends', function (ctx) {
363 return ctx.user.getFriends().then(function(friends) {
364 ctx.body = friends;
365 });
366 })
367 // /users/3 => {"id": 3, "name": "Alex"}
368 // /users/3/friends => [{"id": 4, "name": "TJ"}]
369```
370<a name="module_koa-router--Router.url"></a>
371#### Router.url(path, params) ⇒ <code>String</code>
372Generate URL from url pattern and given `params`.
373
374**Kind**: static method of <code>[Router](#exp_module_koa-router--Router)</code>
375
376| Param | Type | Description |
377| --- | --- | --- |
378| path | <code>String</code> | url pattern |
379| params | <code>Object</code> | url parameters |
380
381**Example**
382```javascript
383var url = Router.url('/users/:id', {id: 1});
384// => "/users/1"
385```
386## Contributing
387
388Please submit all issues and pull requests to the [alexmingoia/koa-router](http://github.com/alexmingoia/koa-router) repository!
389
390## Tests
391
392Run tests using `npm test`.
393
394## Support
395
396If you have any problem or suggestion please open an issue [here](https://github.com/alexmingoia/koa-router/issues).