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.tsexports.cors = {  enable: true,  package: 'egg-cors',}

配置 cors 插件

// src/config/config.default.tsexport 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...