Skip to content

Commit 4b65ff6

Browse files
author
刘正锟
committed
feat: koa
1 parent b8e82f7 commit 4b65ff6

File tree

20 files changed

+2223
-0
lines changed

20 files changed

+2223
-0
lines changed

base/25koa/package-lock.json

Lines changed: 1032 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

base/25koa/package.json

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
{
2+
"name": "25koa",
3+
"version": "1.0.0",
4+
"description": "",
5+
"main": "index.js",
6+
"scripts": {
7+
"test": "echo \"Error: no test specified\" && exit 1"
8+
},
9+
"keywords": [],
10+
"author": "",
11+
"license": "ISC",
12+
"dependencies": {
13+
"ejs": "^3.1.3",
14+
"koa": "^2.13.0",
15+
"koa-better-body": "^3.3.9",
16+
"koa-bodyparser": "^4.3.0",
17+
"koa-router": "^9.1.0",
18+
"koa-session": "^6.0.0",
19+
"koa-static": "^5.0.0",
20+
"koa-views": "^6.3.0"
21+
}
22+
}

base/25koa/src/cookie.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
const Koa = require("koa");
2+
const app = new Koa();
3+
4+
app.use(async (ctx, next) => {
5+
console.log(ctx.url);
6+
if (ctx.url == "/write") {
7+
ctx.cookies.set("name", "zfpx");
8+
ctx.body = "write";
9+
} else {
10+
next();
11+
}
12+
});
13+
app.use(async (ctx) => {
14+
if (ctx.url == "/read") {
15+
ctx.body = ctx.cookies.get("name");
16+
}
17+
});
18+
19+
app.on("error", (err) => {
20+
log.error("server error", err);
21+
});
22+
app.listen(3000, () => {
23+
console.log("服务启动在3000端口");
24+
});

base/25koa/src/ejs.js

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
const Koa = require("koa");
2+
const views = require("koa-views");
3+
const path = require("path");
4+
const app = new Koa();
5+
app.use(
6+
views(path.join(__dirname, "./views"), {
7+
extension: "ejs",
8+
})
9+
);
10+
app.use(async (ctx) => {
11+
await ctx.render("index", { name: "维基百科" });
12+
});
13+
app.listen(3000, () => {
14+
console.log("server is starting at port 3000");
15+
});

base/25koa/src/form.js

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
const Koa = require('koa');
2+
const views = require('koa-views');
3+
const fs = require('fs');
4+
let querystring = require('querystring');
5+
let path = require('path');
6+
let uuid = require('uuid');
7+
const app = new Koa();
8+
app.use(async (ctx, next) => {
9+
if (ctx.method == 'GET') {
10+
ctx.set('Content-Type', 'text/html;charset=utf8');
11+
ctx.body = (
12+
`
13+
<form id="userform" method="POST" enctype="multipa
14+
用户名:<input type="text" name="username">
15+
密码<input type="text" name="password">
16+
头像<input type="file" name="avatar">
17+
<input type="submit">
18+
</form>
19+
`
20+
);
21+
} else if (ctx.method == 'POST') {
22+
let buffers = [];
23+
ctx.req.on('data', function (data) {
24+
buffers.push(data);
25+
});
26+
ctx.req.on('end', function () {
27+
let result = Buffer.concat(buffers);
28+
let type = ctx.headers['content-type'];
29+
let matched = type.match(/\bboundary=(.+)\b/);
30+
if (matched) {
31+
let seperator = '--' + matched[1];
32+
let body = process(seperator, result);
33+
ctx.body = body;
34+
} else {
35+
next();
36+
}
37+
});
38+
ctx.body = 'hello';
39+
} else {
40+
next();
41+
}
42+
});
43+
app.listen(3000);
44+
Buffer.prototype.split = Buffer.prototype.split || function (sep)
45+
let len = Buffer.byteLength(sep);
46+
let parts = [];
47+
let offset = 0;
48+
let pos = -1;
49+
while (-1 != (pos = this.indexOf(sep, offset))) {
50+
parts.push(this.slice(offset, pos));
51+
offset = pos + len;
52+
}
53+
parts.push(this.slice(offset));
54+
return parts;
55+
}
56+
function process(seperator, result) {
57+
let lines = result.split(seperator);
58+
lines = lines.slice(1, -1);
59+
let body = {};
60+
let files = [];
61+
lines.forEach(function (line) {
62+
let [desc, val] = line.split('\r\n\r\n');
63+
desc = desc.toString();
64+
val = val.slice(0, -2);
65+
if (desc.includes('filename')) {//如果是文件的话
66+
let [, line1, line2] = desc.split('\r\n');
67+
let obj1 = querystring.parse(line1, '; ');
68+
let obj2 = querystring.parse(line2, '; ');
69+
let filepath = path.join(__dirname, 'uploads', uuid.v4
70+
fs.writeFileSync(filepath, val);
71+
files.push({
72+
...obj1, filepath
73+
});
74+
} else {
75+
let matched = desc.match(/\bname=(.+)\b/);
76+
if (matched)
77+
body[matched[1]] = val.toString();
78+
}
79+
});
80+
return { body, files };
81+
}

base/25koa/src/index.js

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
const Koa = require("koa");
2+
const app = new Koa();
3+
4+
app.use(async (ctx, next) => {
5+
console.log('ctx: ', ctx);
6+
console.log(1);
7+
const start = Date.now();
8+
await next();
9+
const ms = Date.now() - start;
10+
ctx.set("X-Response-Time", `${ms}ms`);
11+
console.log(11);
12+
});
13+
// logger
14+
app.use(async (ctx, next) => {
15+
console.log(2);
16+
17+
const start = Date.now();
18+
await next();
19+
const ms = Date.now() - start;
20+
console.log(`${ctx.method} ${ctx.url} - ${ms}`);
21+
console.log(22);
22+
});
23+
// response
24+
app.use(async (ctx) => {
25+
console.log(3);
26+
27+
ctx.body = "Hello World";
28+
console.log(33);
29+
});
30+
app.on("error", (err) => {
31+
log.error("server error", err);
32+
});
33+
app.listen(3000, () => {
34+
console.log("服务启动在3000端口");
35+
});
36+
/**
37+
* 1
38+
2
39+
3
40+
33
41+
11
42+
GET / - 3
43+
22
44+
*/

base/25koa/src/index2.js

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
const Koa = require("koa");
2+
const app = new Koa();
3+
app.use(async (ctx) => {
4+
console.log(ctx.method); //获取请求方法
5+
console.log(ctx.url); //获取请求URL
6+
console.log(ctx.query); //获取解析的查询字符串对象
7+
console.log(ctx.querystring); //根据 ? 获取原始查询字符串.
8+
console.log(ctx.headers); //获取请求头对象
9+
ctx.body = ctx.url;
10+
});
11+
app.listen(3000, () => {
12+
console.log("server is starting at port 3000");
13+
});

base/25koa/src/index3.js

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
const Koa = require("koa");
2+
const querystring = require("querystring");
3+
const app = new Koa();
4+
app.use(async (ctx) => {
5+
if (ctx.method == "GET") {
6+
ctx.set("Content-Type", "text/html;charset=utf-8");
7+
ctx.body = `
8+
<form method="POST">
9+
<input name="username" >
10+
<input type="submit">
11+
</form>
12+
`;
13+
} else if (ctx.method == "POST") {
14+
ctx.set("Content-Type", "application/json");
15+
ctx.body = await parseBody(ctx);
16+
} else {
17+
ctx.body = "Not Allowed";
18+
}
19+
});
20+
function parseBody(ctx) {
21+
return new Promise(function (resolve, reject) {
22+
let buffers = [];
23+
ctx.req.on("data", function (data) {
24+
buffers.push(data);
25+
});
26+
ctx.req.on("end", function (data) {
27+
let body = buffers.toString();
28+
body = querystring.parse(body);
29+
resolve(body);
30+
});
31+
ctx.req.on("error", function (errdata) {
32+
reject(err);
33+
});
34+
});
35+
}
36+
app.listen(3000, () => {
37+
console.log("server is starting at port 3000");
38+
});

base/25koa/src/index4.js

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
const Koa = require("koa");
2+
const querystring = require("querystring");
3+
const bodyParser = require("koa-bodyparser");
4+
const app = new Koa();
5+
app.use(bodyParser());
6+
app.use(async (ctx) => {
7+
if (ctx.method == "GET") {
8+
ctx.set("Content-Type", "text/html;charset=utf-8");
9+
ctx.body = `
10+
<form method="POST">
11+
<input name="username" >
12+
<input type="submit">
13+
</form>
14+
`;
15+
} else if (ctx.method == "POST") {
16+
ctx.set("Content-Type", "application/json");
17+
console.log("ctx.request.body: ", ctx.request.body);
18+
ctx.body = ctx.request.body;
19+
} else {
20+
ctx.body = "Not Allowed";
21+
}
22+
});
23+
app.listen(3000, () => {
24+
console.log("server is starting at port 3000");
25+
});

base/25koa/src/index5.js

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
const Koa = require("koa");
2+
const querystring = require("querystring");
3+
const path = require("path");
4+
const convert = require("koa-convert");
5+
const bodyParser = require("koa-better-body");
6+
const app = new Koa();
7+
app.use(
8+
convert(
9+
bodyParser({
10+
uploadDir: path.join(__dirname, "uploads"),
11+
keepExtensions: true,
12+
})
13+
)
14+
);
15+
app.use(async (ctx) => {
16+
if (ctx.method == "GET") {
17+
ctx.set("Content-Type", "text/html;charset=utf-8");
18+
ctx.body = `
19+
<form method="POST" enctype="multipart/form-data">
20+
<input name="username" >
21+
<input name="avatar" type="file" >
22+
<input type="submit">
23+
</form>
24+
`;
25+
} else if (ctx.method == "POST") {
26+
ctx.set("Content-Type", "application/json");
27+
console.log(ctx.request.fields);
28+
const { username, avatar } = ctx.request.fields;
29+
ctx.body = { username, img: avatar[0].path };
30+
} else {
31+
ctx.body = "Not Allowed";
32+
}
33+
});
34+
app.listen(3000, () => {
35+
console.log("server is starting at port 3000");
36+
});

0 commit comments

Comments
 (0)