koa的跨域处理
koa处理跨域
跨域问题如图:
1、安装koa2-cors
npm i koa2-cors
2、main.js中配置
// 处理跨域
const cors = require('koa2-cors');// 配置中间件
// 实例化koa 之后的代码如下:
app.use(cors({
origin: function(ctx) { //设置允许来自指定域名请求
if (ctx.url === '/test') {
return '*'; // 允许来自所有域名请求
}
return 'http://localhost:8081'; //只允许http://localhost:8081这个域名的请求
},
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 = ['https://www.fqniu.xyz', 'http://localhost:8080', '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:8080' //默认允许本地请求8080端口可跨域
},
maxAge: 5, //指定本次预检请求的有效期,单位为秒。
credentials: true, //是否允许发送Cookie
allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], //设置所允许的HTTP请求方法
allowHeaders: ['Content-Type', 'Authorization', 'Accept'], //设置服务器支持的所有头信息字段
exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'] //设置获取其他自定义字段
}))