要求 Node 版本不低于 7.6.0
npm install --save koa2-cors
var Koa = require("koa");
var cors = require("koa2-cors");
var app = new Koa();
app.use(cors());
用于配置 Access-Control-Allow-Origin 头. 可以是一个函数,其第一个参数为ctx
接受逗号分隔的数组,用于设置 Access-Control-Expose-Headers头
用于设置 Access-Control-Max-Age CORS header.
布尔值,用于配置 Access-Control-Allow-Credentials CORS header.
用于配置 Access-Control-Allow-Methods CORS header. 默认值为 ['GET', 'PUT', 'POST', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS']
.
Configures the Access-Control-Allow-Headers CORS header. Expects a comma-delimited array . If not specified, defaults to reflecting the headers specified in the request's Access-Control-Request-Headers header.
var Koa = require('koa');
var cors = require('koa2-cors');
var app = new Koa();
app.use(cors({
origin: function(ctx) {
if (ctx.url === '/test') {
return false;
}
return '*';
},
exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
maxAge: 5,
credentials: true,
allowMethods: ['GET', 'POST', 'DELETE'],
allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
}));
...