关于vue.js:midway-跨域

7次阅读

共计 1485 个字符,预计需要花费 4 分钟才能阅读完成。

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…

正文完
 0