- Koa.js - Resources
- Koa.js - Scaffolding
- Koa.js - Logging
- Koa.js - RESTful APIs
- Koa.js - Database
- Koa.js - Caching
- Koa.js - Compression
- Koa.js - Authentication
- Koa.js - Sessions
- Koa.js - Cookies
- Koa.js - Static Files
- Koa.js - File Uploading
- Koa.js - Form Data
- Koa.js - Templating
- Koa.js - Cascading
- Koa.js - Error Handling
- Koa.js - Redirects
- Koa.js - Response Object
- Koa.js - Request Object
- Koa.js - HTTP Methods
- Koa.js - URL Building
- Koa.js - Routing
- Koa.js - Generators
- Koa.js - Hello World
- Koa.js - Environment
- Koa.js - Overview
- Koa.js - Home
Koa.js Useful Resources
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Koa.js - URL Building
We can now define routes; they are either static or fixed. To use dynamic routes, we need to provide different types of routes. Using dynamic routes allow us to pass parameters and process based on them. Following is an example of a dynamic route.
var koa = require( koa ); var router = require( koa-router ); var app = koa(); var _ = router(); _.get( /:id , sendID); function *sendID() { this.body = The id you specified is + this.params.id; } app.use(_.routes()); app.psten(3000);
To test this go to https://localhost:3000/123. You will get the following response.
You can replace 123 in the URL with anything else and it ll be reflected in the response. Following is a complex example of the above.
var koa = require( koa ); var router = require( koa-router ); var app = koa(); var _ = router(); _.get( /things/:name/:id , sendIdAndName); function *sendIdAndName(){ this.body = id: + this.params.id + and name: + this.params.name; }; app.use(_.routes()); app.psten(3000);
To test this go to https://localhost:3000/things/tutorialspoint/12345.
You can use the this.params object to access all the parameters you pass in the URL. Note that the above two have different paths. They will never overlap. Also if you want to execute the code when you get /things , then you need to define it separately.
Pattern Matched Routes
You can also use regex to restrict URL parameter matching. Let s say you need the id to be five digits long number. You can use the following route definition.
var koa = require( koa ); var router = require( koa-router ); var app = koa(); var _ = router(); _.get( /things/:id([0-9]{5}) , sendID); function *sendID(){ this.body = id: + this.params.id; } app.use(_.routes()); app.psten(3000);
Note that this will only match the requests that have a 5-digit long id. You can use more complex regexes to match/vapdate your routes. If none of your routes match the request, you ll get a Not found message as response.
For example, if we define the same routes as above, on requesting with a vapd URL, we get −
Advertisements