Koa-router
Router Middleware for KOA. Provides RESTful resource routing.
Koa-router
Router middleware for KOA
- 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.
- The support for 405 Method is not allowed and 501 not implemented.
- Multiple route middleware.
- Multiple routers.
- Nestable routers.
- ES7 async/await Support (Koa-router 7.x).
KOA 2.x
See Koa-router 7.x for KOA 2.x and async/await support.
Installation
Install using NPM:
NPM Install Koa-router
API Reference
- 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
Router
Kind: Exported class
New Router ([opts])
Create a new router.
Param |
Type |
Description |
[OPTs] |
Object |
|
[Opts.prefix] |
String |
Prefix router paths |
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 () Orrouter.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 is translated to regular expressions using Path-to-regexp.Query strings is not being considered when matching requests.
Named routes
Routes can optionally has names. This allows generation of URLs and easy renaming of URLs during development.
Multiple middleware
multiple middleware may 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 ();p osts.get ('/', function * (next) {...}); Posts.get ('/:p ID ', 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 prefixed at the router level:
var router = new Router ({
URL parameters
Named route parameters is 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
Param |
Type |
Description |
Path |
String |
|
[Middleware] |
function |
Route middleware (s) |
Callback |
function |
Route callback |
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 would run for any routes this include that path.
Kind: Instance method of Router
Param |
Type |
[Path] |
String |
Middleware |
function |
[...] |
function |
Example
Router.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 is already initialized.
Kind: Instance method of Router
Example
Router.prefix ('/things/:thing_id ')
Router.allowedmethods ([options])? function
Returns separate middleware for responding to OPTIONS requests with a allow header containing the allowed methods, as the well as responding with 405 Method is not allowed and 501 not implemented as appropriate.
Kind: Instance method of Router
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 |
Example
var 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 was equivalent to:
Router.all ('/login ', function * () { this.redirect ('/sign-in '); This.status = 301;});
Kind: Instance method of Router
Param |
Type |
Description |
Source |
String |
URL or route name. |
Destination |
String |
URL or route name. |
Code |
Number |
HTTP Status Code (default:301). |
Router.route (name)? Layer | False
Lookup route with given name.
Kind: Instance method of Router
Router.url (name, params)? String | Error
Generate URL for route. Takes the route name and a map of namedWemall Open Source Micro-mall, mall, mall source code, level three distribution, micro-fresh, micro-fruit, micro-takeaway, micro-ordering---professional systemWemall Address: http://www.wemallshop.com
code Source: HTTP://JS.KOAHUB.COM/HOME/FEATURE/KOA-JWT
Koahub platform based on node. JS developed KOA Router routing plug-in code information details