-
Notifications
You must be signed in to change notification settings - Fork 0
/
demo7.js
57 lines (50 loc) · 1.4 KB
/
demo7.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
54
55
56
57
// POST请求参数获取
const Koa = require("koa");
const qs = require("qs");
const app = new Koa();
const port = 5200;
// 解析上下文里node原生请求的POST参数
function parsePostData(ctx) {
return new Promise((resolve, reject) => {
try {
let postdata = "";
ctx.req.addListener("data", (data) => {
postdata += data;
});
ctx.req.addListener("end", function () {
let parseData = qs.parse(postdata);
resolve(parseData);
});
} catch (err) {
reject(err);
}
});
}
app.use(async (ctx) => {
if (ctx.url === "/" && ctx.method === "GET") {
// 当GET请求时候返回表单页面
let html = `
<h1>koa2 request post demo</h1>
<form method="POST" action="/">
<p>userName</p>
<input name="userName" /><br/>
<p>nickName</p>
<input name="nickName" /><br/>
<p>email</p>
<input name="email" /><br/>
<button type="submit">submit</button>
</form>
`;
ctx.body = html;
} else if (ctx.url === "/" && ctx.method === "POST") {
// 当POST请求的时候,解析POST表单里的数据,并显示出来
let postData = await parsePostData(ctx);
ctx.body = postData;
} else {
// 其他请求显示404
ctx.body = "<h1>404!!! o(╯□╰)o</h1>";
}
});
app.listen(port, () => {
console.log("访问地址为: http://localhost:%s", port);
});