![Koa.js Tutorial](/koajs/images/koa-mini-logo.jpg)
- Koa.js Tutorial
- Koa.js - Home
- Koa.js - Overview
- Koa.js - Environment
- Koa.js - Hello World
- Koa.js - Generators
- Koa.js - Routing
- Koa.js - URL Building
- Koa.js - HTTP Methods
- Koa.js - Request Object
- Koa.js - Response Object
- Koa.js - Redirects
- Koa.js - Error Handling
- Koa.js - Cascading
- Koa.js - Templating
- Koa.js - Form Data
- Koa.js - File Uploading
- Koa.js - Static Files
- Koa.js - Cookies
- Koa.js - Sessions
- Koa.js - Authentication
- Koa.js - Compression
- Koa.js - Caching
- Koa.js - Database
- Koa.js - RESTful APIs
- Koa.js - Logging
- Koa.js - Scaffolding
- Koa.js - Resources
- Koa.js Useful Resources
- Koa.js - Quick Guide
- Koa.js - Useful Resources
- Koa.js - Discussion
Koa.js - Routing
Web frameworks provide resources such as HTML pages, scripts, images, etc. at different routes. Koa does not support routes in the core module. We need to use the Koa-router module to easily create routes in Koa. Install this module using the following command.
npm install --save koa-router
Now that we have Koa-router installed, let’s look at a simple GET route example.
var koa = require('koa'); var router = require('koa-router'); var app = koa(); var _ = router(); //Instantiate the router _.get('/hello', getMessage); // Define routes function *getMessage() { this.body = "Hello world!"; }; app.use(_.routes()); //Use the routes defined using the router app.listen(3000);
If we run our application and go to localhost:3000/hello, the server receives a get request at route "/hello". Our Koa app executes the callback function attached to this route and sends "Hello World!" as the response.
![Routing Hello](/koajs/images/routing_hello.jpg)
We can also have multiple different methods at the same route. For example,
var koa = require('koa'); var router = require('koa-router'); var app = koa(); var _ = router(); //Instantiate the router _.get('/hello', getMessage); _.post('/hello', postMessage); function *getMessage() { this.body = "Hello world!"; }; function *postMessage() { this.body = "You just called the post method at '/hello'!\n"; }; app.use(_.routes()); //Use the routes defined using the router app.listen(3000);
To test this request, open your terminal and use cURL to execute the following request
curl -X POST "https://localhost:3000/hello"
![Curl Routing](/koajs/images/routing_curl.jpg)
A special method, all, is provided by express to handle all types of http methods at a particular route using the same function. To use this method, try the following −
_.all('/test', allMessage); function *allMessage(){ this.body = "All HTTP calls regardless of the verb will get this response"; };