koa解決跨域的方法

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'; //只允許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'] //設置獲取其他自定義字段
    })
);

參考鏈接1

參考鏈接2

參考鏈接3

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章