跳到主要内容

koa-cors

2024年10月17日
柏拉文
越努力,越幸运

一、认识


@koa/cors 是一个 Koa 中间件,用于处理跨域资源共享(CORS)请求。CORS 是一种安全机制,允许服务器控制哪些域可以访问其资源,特别是在 Web 应用中,当前端和后端位于不同的域时,CORS 的配置就显得尤为重要。

二、API


三、语法


const Koa = require('koa');
const KoaCors = require('@koa/cors');
const Router = require('koa-router');

const app = new Koa();
const router = new Router();

app.use(KoaCors({
origin: 'http://example.com', // 允许来自特定域的请求
allowMethods: ['GET', 'POST'], // 允许的方法
allowHeaders: ['Content-Type', 'Authorization'], // 允许的请求头
}));

router.get('/data', async (ctx) => {
ctx.body = { message: 'Hello, CORS!' };
});

app.use(router.routes()).use(router.allowedMethods());

app.listen(3000, () => {
console.log('Server listening on port 3000');
});