Previous article introduces the basic operation of koa2 (sit down sit down), but always return to the same HTML seems impossible, so now we need to deal with the URL.
Something to point directly to the high point, we need to be able to handle a URL of middleware, it is called: KOA-Router :
npm install koa-router
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const Koa =
require(
'koa');
const router =
require(
'koa-router')();
const
app Koa = ();
router.get(
'/hello/:name',
async(ctx, next) => {
var name = ctx.params.name;
ctx.response.body =
`<h1>Hello, {$name}!</h1>`;
});
router.get(
'/',
async(ctx, next) => {
ctx.response.body =
'<h1>Index Page</h1>';
});
app.use(router.routes());
app.listen(
3000);
console.log(
'Server listen on port 3000...');
The code here, will visit the URL localhost: return to Index Page 3000, while visiting localhost: 3000 / hello / louis when the display is Hello, louis, and this router is for us to achieve the ability to handle the URL!. Note, at the time of the introduction router, is one more brackets, indicating that the router we introduce is an object, and in front of Koa introduced is actually a class (so it is capitalized ~).