1.自行添加一箇中間件
app.use(async (ctx, next)=> {
ctx.set('Access-Control-Allow-Origin', '*');
ctx.set('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
ctx.set('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
if (ctx.method == 'OPTIONS') {
ctx.body = 200;
} else {
await next();
}
});
2.使用koa2-cors
2.1先下載
npm install koa2-cors --save
2.2使用
const Koa = require('koa');
const cors = require('koa2-cors');
const app = new Koa();
app.use(cors());
app.use(
cors({
origin: function(ctx) {
if (ctx.url === '/test') {
return '*';
}
return 'http://localhost:8080';
},
maxAge: 5,
credentials: true,
allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
exposeHeaders: ['WWW-Authenticate', 'Server-Authorization']
})
);
參考鏈接1
參考鏈接2
參考鏈接3