安装模块
npm install --save koa-router
或者配置文件package.json中依赖配置如下:
{
"dependencies": {
"koa": "^2.13.1",
"koa-router": "^10.0.0",
...
},
...
}
利用koa-router来处理URL,代码如下:
const Koa = require('koa');
const Router = require('koa-router');
// 创建一个Koa对象表示web app本身:
const app = new Koa();
const router = new Router();
// 对于任何请求,app将调用该异步函数处理请求:
app.use(async (ctx, next) => {
console.log(`Process ${ctx.request.method} ${ctx.request.url}...`);
await next();
});
router.get('/', async (ctx, next) => {
ctx.response.body = `<h1>Hello, Koa2</h1>`;
});
router.get('/hello/:name', async (ctx, next) => {
let name = ctx.params.name;
ctx.response.body = `<h1>Hello, ${name}</h1>`
});
app.use(router.routes());
// 在端口3000监听:
app.listen(3000);
console.log('app started at port 3000...');