1const { APP_PORT } = require("./env/index.js")
2const Koa = require("koa")
3const router = require("./router/index.js")
4const { koaBody } = require("koa-body")
5const cors = require("@koa/cors") // [!code focus]
6
7const app = new Koa()
8
9// 使用 koa-body 中间件
10app.use(
11 koaBody({
12 multipart: true,
13 formidable: {
14 uploadDir: "./uploads",
15 keepExtensions: true,
16 },
17 json: true,
18 form: true,
19 text: true,
20 })
21)
22
23// 应用 cors 中间件,允许所有来源的跨域请求 // [!code focus]
24app.use( // [!code focus]
25 cors({ // [!code focus]
26 origin: (ctx) => ctx.get("Origin") || "*", // [!code focus]
27 }) // [!code focus]
28) // [!code focus]
29
30// 使用路由中间件
31app.use(router.routes()).use(router.allowedMethods())
32
33app.listen(APP_PORT, () => {
34 console.log(`Server running on http://localhost:${APP_PORT}`)
35})