1. What route is?
In koa, the nature of the route is a middleware
Routing determines how different URL is different execution
2. koa-router
In koa, we use koa-router for routing
1. AnSo koa-router
npm i koa-router --save
2. use koa-router
the require Koa = const ( 'KOA' ) // 1. introducing route const = the require Router ( 'KOA-Router' ) const App = new new Koa () // 2. Examples of routes const = Router new new Router () / * . 3 . implementing routing instantiated a Router, to keep up request method (get, post ...) internal method written routed path, and then write the content may be a function of the middleware * / router.get ( '/ ', (CTX) => { ctx.body = "this is the home" }) router.get ( ' / users', (CTX) => { ctx.body = "this is a list of users" }) router.post ( '/ Users', (CTX) => { CTX.body = "Create User" }) / * GET request carries parameters used: mode parameter name acquisition parameters carried in the request, using ctx.params parameter name. * / Router.get ( '/ Users /: ID', (CTX ) => { ctx.body = `this is a list of user ctx.params.id} {` $ // this is a list of user Hao }) // registered route app.use (router.routes ()) app.listen ( 3002 )
Knowledge Point: Get the get request header parameters can be obtained by carrying ctx.params parameter name.
3. Route advanced knowledge
1. route prefix
In the above code, we have two sections of the route. Is a '/', the other is '/ users'. Easy to operate and to simplify the code, we can add a prefix to the routing
Here is the code to add the prefix is added above:
the require Koa = const ( 'KOA' ) const Router = the require ( 'KOA-Router' ) const App = new new Koa () const Router = new new Router () // prefixes const = usersRouter new new Router ({prefix: '/ Users ' }) router.get ( ' / ', (CTX) => { ctx.body = "this is the home" }) // use the routing prefix, we can replace all with router / users with usersRouter usersRouter. GET ( '/', (CTX) => { ctx.body = "this is a list of users" }) usersRouter.post ( '/', (CTX) =>{ Ctx.body = "Create a user" }) UsersRouter.get ( '/: ID', (CTX) => { ctx.body = `This is a list of user ctx.params.id} {` $ }) // NOTE! We added a new prefix route, do not forget to register app.use (router.routes ()) app.use (usersRouter.routes ()) app.listen ( 3002)
Summary: In example 1 by addition of routing {prefix: 'pathname'} way to add a prefix
2 After instantiating a new route, do not forget to register
2. Multi-routing middleware
In route, we can add multiple middleware to implement routing functions.
Commonly used in multi-user login middleware routing, certification authority
In the above example, creating a user route, we assume that there must be logged in order to do this, we can add a login authentication middleware in the route.
// assumed auth middleware user login authentication is usersRouter.post ( '/', auth, (CTX) => { ctx.body = "Create User" })