koa2-cors设置允许指定单个域名、多个域名、所有域名跨域

2,219 阅读1分钟

允许所有域名跨域访问

const cors = require('koa2-cors');// CORS是一个W3C标准,全称是"跨域资源共享"
app.use(cors()); //全部允许跨域

你没有看错,就这么简单,在你koa项目入口文件中引入一个中间件koa2-cors,然后执行下它的cors()方法就完了,但考虑到安全性问题,我们上线后并不希望所有人可以去跨域访问接口,那么如何做?

指定单个域名跨域

app.use(
    cors({
        origin: function(ctx) { //设置允许来自指定域名请求
            return 'http://localhost:8080'; //只允许http://localhost:8080这个域名的请求
        },
        maxAge: 5, //指定本次预检请求的有效期,单位为秒。
        credentials: true, //是否允许发送Cookie
        allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], //设置所允许的HTTP请求方法
        allowHeaders: ['Content-Type', 'Authorization', 'Accept'], //设置服务器支持的所有头信息字段
        exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'] //设置获取其他自定义字段
    })
);

设置多个域名可跨域

app.use(
    cors({
        origin: function(ctx) { //设置允许来自指定域名请求
            const whiteList = ['http://weipxiu.com','http://localhost:8081']; //可跨域白名单
            let url = ctx.header.referer.substr(0,ctx.header.referer.length - 1);
            if(whiteList.includes(url)){
                return url //注意,这里域名末尾不能带/,否则不成功,所以在之前我把/通过substr干掉了
            }
            return 'http://localhost::3000' //默认允许本地请求3000端口可跨域
        },
        maxAge: 5, //指定本次预检请求的有效期,单位为秒。
        credentials: true, //是否允许发送Cookie
        allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], //设置所允许的HTTP请求方法
        allowHeaders: ['Content-Type', 'Authorization', 'Accept'], //设置服务器支持的所有头信息字段
        exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'] //设置获取其他自定义字段
    })
);