180 条记录
15 私有链接
15 私有链接
安装koa2-cors:
npm install koa2-cors
const Koa = require('koa');
const cors = require('koa2-cors');
const app = new Koa();
app.use(cors({
origin: (ctx) => {
// 限制特定域名或根据条件动态设置
if (ctx.request.header.origin === 'http://allowed-origin.com') {
return 'http://allowed-origin.com';
}
return '*'; // 允许所有域名
},
allowMethods: ['GET', 'POST', 'PUT', 'DELETE'], // 限制允许的请求方法
allowHeaders: ['Content-Type', 'Authorization', 'Accept'], // 指定允许的请求头
credentials: true, // 是否允许发送cookie
}));
// 其他中间件
app.use(async ctx => {
ctx.body = 'CORS enabled!';
});
app.listen(3000);
高级注意事项:
安全性考虑:
生产环境中尽量避免使用'*'作为origin值,特别是如果credentials设置为true时,这会导致安全隐患,确保origin只允许可信域名。
动态控制:
根据不同请求动态返回CORS设置,特别是针对不同的API,可以使用自定义逻辑来动态决定是否允许跨域请求。
复杂请求:
某些带有自定义请求头或非简单方法(如PUT、DELETE)的请求是“预检请求”,确保在返回响应头时正确处理Access-Control-Allow-Headers和Access-Control-Allow-Methods。
这样就可以在Koa2中灵活地控制和管理CORS设置。
使用'*'作为origin值
const Koa = require('koa');
const cors = require('koa2-cors');
const app = new Koa();
app.use(cors({
origin: '*', // 允许所有域名
allowMethods: ['GET', 'POST', 'PUT', 'DELETE'], // 允许的请求方法
allowHeaders: ['Content-Type', 'Authorization', 'Accept'], // 允许的请求头
credentials: false, // 开发环境下不需要cookie,设置为false
}));
app.use(async ctx => {
ctx.body = 'CORS enabled with * origin!';
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});