Appearance
koa-cors
简介
koa-cors 是一个用于处理跨域资源共享(CORS)的中间件,它可以帮助你轻松地在 Koa 应用中启用和配置 CORS 策略,使你的 API 能够安全地响应来自不同域的请求。
安装
bash
npm install @koa/cors基本使用
javascript
const Koa = require('koa');
const cors = require('@koa/cors');
const app = new Koa();
// 注册中间件
app.use(cors());
app.use(async (ctx) => {
ctx.body = { message: '支持跨域访问' };
});
app.listen(3000);高级配置
javascript
const Koa = require('koa');
const cors = require('@koa/cors');
const app = new Koa();
app.use(cors({
// 允许的源,可以是字符串或数组
origin: ['http://localhost:8080', 'https://example.com'],
// 允许的请求方法
allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
// 允许的请求头
allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
// 允许发送 Cookie
credentials: true,
// 设置预检请求的有效期(秒)
maxAge: 5400,
// 允许暴露的响应头
exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
// 是否通过函数处理 origin
origin: (ctx) => {
const origin = ctx.get('Origin');
if (origin.startsWith('http://localhost')) {
return origin;
}
return false; // 不允许其他来源
}
}));
app.use(async (ctx) => {
ctx.body = { message: '已配置跨域策略' };
});
app.listen(3000);注意事项
- 在生产环境中,应该明确指定允许的源,避免使用通配符 '*'
- 如果需要发送 Cookie,必须设置 credentials: true,且 origin 不能为 '*'
- 预检请求(OPTIONS)的处理会自动完成,无需手动处理
- 建议根据实际需求配置 allowMethods 和 allowHeaders,避免过度开放
- 在使用 credentials: true 时,前端也需要相应配置 withCredentials: true