koa体验

1 安装

1
npm i koa

2 使用

1
2
3
4
5
6
7
8
const Koa = require('koa')
const app = new Koa()
app.use(async (ctx, next) => {
await next();
ctx.response.type = 'text/html';
ctx.response.body = '<h1>Hello, koa2!</h1>';
})
app.listen(3000)

3 使用路由中间件

1
2
3
4
5
6
7
8
9
10
npm i koa-router

const router = require('koa-router')()

router.get('/hello/:name', async (ctx, next) => {
const name = ctx.params.name;
ctx.response.body = `<h1>Hello, ${name}!</h1>`;
});

app.use(router.routes())

4 使用koa-bodyparser处理post请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
npm i koa-bodyparser

const bodyParser = require('koa-bodyparser');

app.use(bodyParser());

router.post('/signin', async (ctx, next) => {
const name = ctx.request.body.name || '',
password = ctx.request.body.password || '';
console.log(`signin with name: ${name}, password: ${password}`);
if (name === 'koa' && password === '12345') {
ctx.response.body = `<h1>Welcome, ${name}!</h1>`;
} else {
ctx.response.body = `<h1>Login failed!</h1>
<p><a href="/">Try again</a></p>`;
}
})

完整代码

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
const Koa = require('koa');
const router = require('koa-router')()
const bodyParser = require('koa-bodyparser');

const app = new Koa();
app.use(bodyParser());


// log request URL:
app.use(async (ctx, next) => {
console.log(`Process ${ctx.request.method} ${ctx.request.url}...`);
await next();
});

app.use(async (ctx, next) => {
await next();
ctx.response.type = 'text/html';
ctx.response.body = '<h1>Hello, koa2!</h1>';
})

// add url-route:
router.get('/hello/:name', async (ctx, next) => {
const name = ctx.params.name;
ctx.response.body = `<h1>Hello, ${name}!</h1>`;
});

router.get('/', async (ctx, next) => {
ctx.response.body = `<h1>Index</h1>
<form action="/signin" method="post">
<p>Name: <input name="name" value="koa"></p>
<p>Password: <input name="password" type="password"></p>
<p><input type="submit" value="Submit"></p>
</form>`;
});

router.post('/signin', async (ctx, next) => {
const name = ctx.request.body.name || '',
password = ctx.request.body.password || '';
console.log(`signin with name: ${name}, password: ${password}`);
if (name === 'koa' && password === '12345') {
ctx.response.body = `<h1>Welcome, ${name}!</h1>`;
} else {
ctx.response.body = `<h1>Login failed!</h1>
<p><a href="/">Try again</a></p>`;
}
})


app.use(router.routes())

app.listen(3000)
作者

建指所向

发布于

2021-09-24

更新于

2023-11-07

许可协议