博客 / 詳情

返回

midway 跨域

midway 跨域

最近準備上手midway.js來開發點東西。開發的API,在前端(vue+axios)調用時總是提示跨域,但ajax又能調用。浪費了很多時間,在此記錄一下。

midway 配置:

之前搜索過跨域問題解決辦法:

csrf 配置

//在”src/config/config.default.ts”,添加代碼如下

export default (appInfo: EggAppInfo) => {
  const config = <DefaultConfig> {};
  ……
  // 跨域  @midwayjs/web 默認添加了此項配置的
  config.security = {
    csrf: {
      enable: false, 
    },
    
    domainWhiteList: ['http://127.0.0.1:9384'], // 允許跨域的域名
  };
  ……
}

<font color=red>提示:很多文檔説的解決跨域,這樣一設置就OK了,實踐告訴我關這個配置還是不行的!!</font>

security 配置項是eggjs中對安全的一項配置,詳見: 安全威脅 CSRF 的防範

CORS 配置

安裝 egg-cors

$ npm i egg-cors --save 

配置插件啓用

// src/config/plugin.ts
exports.cors = {
  enable: true,
  package: 'egg-cors',
}

配置 cors 插件

// src/config/config.default.ts
export const cors = {
  // {string|Function} origin: '*',
  // {string|Array} allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH'
};

如果這個地方設置了origin: '*',那麼在security下設置的domainWhiteList無用了

另一種設置方法

origin(ctx) {
     // return "*"; // 允許來自所有域名請求
     // return ctx.header.origin;// 當*無法使用時,使用這句,同樣允許所有跨域
     // return 'http://localhost:8080'; //單個跨域請求
     // 允許多個跨域
     const allowCors = [
       'http://localhost:9384',
       'http://127.0.0.1:9384',
       'http://172.16.92.62:9384',
     ];
     return allowCors.indexOf(ctx.header.origin) > -1 ? ctx.header.origin : '';
},

<font color=red>經測試allowMethods 好像不管用</font>

如果只想特定域名,需要在 security 插件處配置。詳見 上面csrf

domainWhiteList: ['http://127.0.0.1:9384'], // 允許跨域的域名
經測試:在security 下指定了此項,config.cors不用設置也行

vue axios

如果你在axios設置中添加了<font color=red> withCredentials=true</font> 這個選項,那麼請求也會造成跨域

參考:https://blog.csdn.net/hermits...

後端設置方法:

config.cors{
     credentials: true, 
     origin: 'http://127.0.0.1:9384', // 注意,這個地方不能使用 * 可以使用上面介紹的函數方式,必須要包含你的前端地址
}

其他框架

參考: https://www.yuque.com/midwayj...

user avatar
0 位用戶收藏了這個故事!

發佈 評論

Some HTML is okay.