-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
60 lines (49 loc) · 1.11 KB
/
index.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
58
59
60
const Koa = require("koa");
const Router = require("koa-router");
const session = require("koa-session");
const bodyParser = require("koa-bodyparser");
const fs = require("fs");
const app = new Koa();
app.keys = ["sekrit"];
app.use(bodyParser());
app.use(session(app));
const r = new Router();
r.get("/", ctx => {
ctx.type = "html";
ctx.body = fs.createReadStream("./public/index.html");
});
r.get("/session", ctx => {
const sess = ctx.session;
ctx.body = sess;
});
r.post("/session", ctx => {
const { body } = ctx.request;
console.log(body);
if (!body) {
ctx.body = "ERROR";
}
ctx.session = { body };
ctx.body = "OK";
});
r.get("/static/:file", async ctx => {
console.log("Hit static");
const { file } = ctx.params;
const fr = function() {
return new Promise(function(resolve, reject) {
fs.readFile("./public/" + file, (err, buf) => {
if (err) {
reject(err);
}
resolve(buf);
});
});
};
try {
ctx.type = file.split(".")[1];
ctx.body = await fr();
} catch {
ctx.throw(404);
}
});
app.use(r.routes());
app.listen(3000);