-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp_router.js
53 lines (39 loc) · 1.2 KB
/
app_router.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// 导入koa,和koa 1.x不同,在koa2中,我们导入的是一个class,因此用大写的Koa表示:
const Koa = require('koa');
// 注意require('koa-router')返回的是函数:
const router = require('koa-router')();
// 创建一个Koa对象表示web app本身:
const app = new Koa();
// 对于任何请求,app将调用该异步函数处理请求:
// app.use(async (ctx, next) => {
// if (ctx.request.path === '/') {
// ctx.response.body = 'index page';
// } else {
// await next();
// }
// });
// app.use(async (ctx, next) => {
// if (ctx.request.path === '/test') {
// ctx.response.body = 'TEST page';
// } else {
// await next();
// }
// });
// log request URL:
// app.use(async (ctx, next) => {
// console.log(`Process ${ctx.request.method} ${ctx.request.url}...`);
// await next();
// });
// add url-route:
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</h1>';
});
// add router middleware:
app.use(router.routes());
// 在端口3000监听:
app.listen(3200);
console.log('app started at port 3200...');