-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
67 lines (57 loc) · 1.39 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
61
62
63
64
65
66
67
const Koa = require("koa");
const Router = require("koa-router");
const logger = require("koa-logger");
const bodyParser = require("koa-bodyparser");
const fs = require("fs");
const path = require("path");
const { init: initDB, Counter } = require("./db");
const router = new Router();
const homePage = fs.readFileSync(path.join(__dirname, "index.html"), "utf-8");
// 首页
router.get("/", async (ctx) => {
ctx.body = homePage;
});
// 更新计数
router.post("/api/count", async (ctx) => {
const { request } = ctx;
const { action } = request.body;
if (action === "inc") {
await Counter.create();
} else if (action === "clear") {
await Counter.destroy({
truncate: true,
});
}
ctx.body = {
code: 0,
data: await Counter.count(),
};
});
// 获取计数
router.get("/api/count", async (ctx) => {
const result = await Counter.count();
ctx.body = {
code: 0,
data: result,
};
});
// 小程序调用,获取微信 Open ID
router.get("/api/wx_openid", async (ctx) => {
if (ctx.request.headers["x-wx-source"]) {
ctx.body = ctx.request.headers["x-wx-openid"];
}
});
const app = new Koa();
app
.use(logger())
.use(bodyParser())
.use(router.routes())
.use(router.allowedMethods());
const port = process.env.PORT || 80;
async function bootstrap() {
await initDB();
app.listen(port, () => {
console.log("启动成功", port);
});
}
bootstrap();