-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.ts
72 lines (65 loc) · 1.73 KB
/
app.ts
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
68
69
70
71
72
import Koa from "koa";
import koaBody from "koa-body";
import views from "koa-views";
import koaStatic from "koa-static";
import consola from "consola";
import path from "path";
import Router from "koa-router";
import cors from "koa2-cors";
import userRouter from "./routes/user";
import homeRouter from "./routes";
const router = new Router();
const app = new Koa();
app.use(
cors({
origin: function (ctx) {
// 设置允许来自指定域名请求
if (ctx.url === "/test") {
return "*";
}
return "http://localhost:8080";
},
maxAge: 5,
credentials: true,
allowMethods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
allowHeaders: ["Content-Type", "Authorization", "Accept"],
exposeHeaders: ["WWW-Authenticate", "Server-Authorization"],
})
);
app.use(
koaBody({
multipart: true,
formidable: {
// the max size of uploading file
maxFileSize: 200 * 1024 * 1024,
},
})
);
app.use(
views(path.join(__dirname, "./views"), {
extension: "ejs",
})
);
// 静态资源目录(相对入口文件app.ts)
const staticPath = "./static";
app.use(koaStatic(path.join(__dirname, staticPath)));
// 子路由
app.use(homeRouter.routes()).use(homeRouter.allowedMethods());
app.use(userRouter.routes()).use(router.allowedMethods());
app.use(router.routes()).use(router.allowedMethods());
// error-handling
app.on("error", (err, ctx) => {
console.error("server error", err, ctx);
});
/**
* Create HTTP server.
*/
const host = process.env.HOST || "localhost";
const port = Number(process.env.PORT) || 3000;
const server = app.listen(port, host, () => {
consola.ready({
message: `http server listening on http://${host}:${port}`,
badge: true,
});
});
server.timeout = 60000;