跨域配置


    步骤 1:安装跨域中间件

    首先,你需要安装 @koa/cors 包来处理跨域请求。在你的 Koa 项目目录下运行以下命令:

    pnpm add @koa/cors

    步骤 2:配置跨域中间件

    安装完成后,我们需要在 Koa 应用中配置跨域中间件。以下是配置跨域资源共享(CORS)的示例代码:

    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})

    通过以上步骤,你的 Koa 应用将能够处理来自不同源的请求,实现了跨域资源共享(CORS)。这使得前端应用能够从不同的域名安全地请求后端服务。