eggjs 跨域訪問

eggjs 跨域訪問

背景

因爲前端項目是Vue構建,爲了方便調試,故而設置可跨域訪問。

步驟

1.添加插件 egg-cors。

npm i egg-cors -S

2.啓用插件 egg-cors:

在 plugin.js 中:

exports.cors = {
  enable: true,
  package: 'egg-cors',
};

3.在config.default.js中配置:

  config.security = {
    csrf: {
      enable: false,
    },
      // 配置白名單
    domainWhiteList: [ 'http://localhost:8080' ],
  };
  config.cors = {
    allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH,OPTIONS',
  };

以上即可。

但是有一個問題,這樣設置後,session和cookie確實不見了。如果想要獲取session和cookie可以在config.default.js添加配置:

config.cors = {
    credentials: true,
    allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH,OPTIONS',
  };

然後在發送跨域請求的時候附帶參數:credentials = true,

比如我用的 flyio,做的網絡請求可以這樣:

// 設置攔截器
fly.interceptors.request.use((request)=>{
    // 以下兩種均可
    // request.withCredentials = true;
    request.body.credentials = true;
    return request;
});

其他框架也是如此,只要添加添加該請求參數即可。

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