【插件】cors:vscode cors扩展 - 解决跨域开发最终版

说在前头

解决跨域的方式不下7 8种,类似的文章我也发表过,但开发路上总会遇到一些奇奇怪怪的限制,让你始终没法easy调试,这次我干脆写了个vscode扩展,伴随开发工具一起完灭Access-Control-Allow-Origin


一、下载

download

vscode扩展应用商店搜索“cors”下载即可


二、如何使用

1、开启

ui

右下角会显示新的icon,点击他即可开启内置服务

icon

start

listening
至此开启了本地端口1337的监听

2.1、ajax联调(get示例 —— lofter)

借用lofter的API尝试

$.ajax({
    type: "get",
    url: "http://www.lofter.com/trade/reward/isOpen",
    success: function (res) {
      console.log(res);
    }
  });

当前请求会报跨域错误,将以上转换为

var VSCODE_CORS_URL = {
  key: "http://localhost:1337",
  proxy: "http://www.lofter.com"
};
$.ajax({
  type: "get",
  url: "http://localhost:1337/trade/reward/isOpen?VSCODE_CORS=" +
    JSON.stringify(VSCODE_CORS_URL),
  success: function (res) {
    console.log(res);
  }
});

ok

返回成功

2.2、ajax联调(post示例 —— 掘金)

借用juejin的API尝试

$.ajax({
  type: "post",
  url: "https://web-api.juejin.im",
  contentType: "application/json;charset=UTF-8",
  data: JSON.stringify({
    operationName: "",
    query: "",
    variables: {
      limit: 10,
      excluded: []
    },
    extensions: {
      query: {
        id: "5a924f4574e04d67b2ae5df189e8423d"
      }
    }
  }),
  success: function (res) {
    console.log(res);
  }
});

当前请求会报跨域错误,将以上转换为

var VSCODE_CORS_URL = {
  key: "http://localhost:1337",
  proxy: "https://web-api.juejin.im",
  other: {
    requestHeaders: {
      "X-Agent": "Juejin/Web"
    }
  }
};
$.ajax({
  type: "post",
  url: "http://localhost:1337/query?VSCODE_CORS=" +
    JSON.stringify(VSCODE_CORS_URL),
  contentType: "application/json;charset=UTF-8",
  data: JSON.stringify({
    operationName: "",
    query: "",
    variables: {
      limit: 10,
      excluded: []
    },
    extensions: {
      query: {
        id: "5a924f4574e04d67b2ae5df189e8423d"
      }
    }
  }),
  success: function (res) {
    console.log(res);
  }
});

ok2

返回成功

2.3、ajax联调(代理多地址模式)(version 0.2.6新增)

处理本地联调多个不同域的情况

var VSCODE_CORS_URL = [
  {
    key: "http://localhost:1337",
    proxy: "https://web-api.juejin.im",
    other: {
      requestHeaders: {
        "X-Agent": "Juejin/Web"
      }
    }
  },
  {
    key: "http://localhost:1337",
    proxy: "http://www.lofter.com"
  },
  // more...
];
$.ajax({
  type: "post",
  url:
    "http://localhost:1337/query?VSCODE_PROXY=https://web-api.juejin.im&VSCODE_CORS=" +
    JSON.stringify(VSCODE_CORS_URL),
  contentType: "application/json;charset=UTF-8",
  data: JSON.stringify({
    operationName: "",
    query: "",
    variables: {
      limit: 10,
      excluded: []
    },
    extensions: {
      query: {
        id: "5a924f4574e04d67b2ae5df189e8423d"
      }
    }
  }),
  success: function(res) {
    console.log(res);
  }
});
$.ajax({
  type: "get",
  url:
    "http://localhost:1337/trade/reward/isOpen?VSCODE_PROXY=http://www.lofter.com&VSCODE_CORS=" +
    JSON.stringify(VSCODE_CORS_URL),
  success: function(res) {
    console.log(res);
  }
});

ok3

ok4
返回成功

2.4、ajax联调(post + multipart/form-data示例)(version 0.4.0新增)

let formData = new FormData()
formData.append('file', e.files[0]) // input dom file

$.ajax({
	url: 'xxx',
	processData: false, // 取消数据解析
	contentType: false, // 取消请求头 - 注意:在jq下会自适应为multipart文件传输方式,但axios须手动设置头
	// axios 请求方式
	// headers: {
    //   'Content-Type': 'multipart/form-data',
    // },
	data: formData,
	type: 'post',
	success: res => {},
	error: res => {}
})

将以上转换为

var VSCODE_CORS_URL = {
  key: "http://localhost:1337",
  proxy: "xxx",
  other: {
    requestHeaders: {
      // do something
    }
  }
};

let formData = new FormData()
formData.append('file', e.files[0]) // input dom file

$.ajax({
	url: 'xxx?VSCODE_CORS=' + JSON.stringify(VSCODE_CORS_URL),
	processData: false,
	contentType: false,
	data: formData,
	type: 'post',
	success: res => {},
	error: res => {}
})

返回成功

3、关闭

close


三、API

因为设计的非常简单,所以目前API配置仅有3个

  1. key(指向当前cors起的服务器地址)
  2. proxy(指向请求的目标地址)
  3. other(其他相关配置项)

关于other,目前给开发者提供了requestHeaders的变更

var VSCODE_CORS_URL = {
  key: "http://localhost:XX",
  proxy: "https://XX",
  other: {
    requestHeaders: {
      "X-Agent": "XX",
      "Cookie": "XX",
      // more
    }
  }
};

扩展内部默认为axios,以上requestHeaders会被以下源码处理,如有相同可被覆盖

headers: {
  'Accept': '*/*',
  'Accept-Encoding': 'utf-8',
  'Accept-Language': 'zh-CN,zh;q=0.8',
  'Host': Host,
  'Origin': Host,
  'Referer': 'http://' + Host,
  'Connection': 'keep-alive',
  'Cookie': "",
  ...requestHeaders
}

四、自测情况

Type

  • Get √
  • Post + application/json √
  • Post + application/x-www-form-urlencoded √

0.4.0 新增

  • Post + multipart/form-data √

Lib

  • JQ √
  • axios √

五、QA

1、vscode cors扩展非常重视请求头,请仔细核对你当前的请求方式(Request Headers Content-Type),例如用“post+application/json”方式,是无法传参给“multipart/form-data”接收并处理转发的
2、返回失败,多数是因为Cookie过期,请重新添写,少数是因为服务端接收方式与请求端不同,仔细查看请求头,区分线上可交互环境与线下交互环境的差别,注意是否有私有请求头

关于

make:o︻そ╆OVE▅▅▅▆▇◤(清一色天空)

blog:http://blog.csdn.net/mcky_love

掘金:https://juejin.im/user/59fbe6c66fb9a045186a159a/posts

lofter:http://zcxy-gs.lofter.com/

sf:https://segmentfault.com/u/mybestangel

git:https://github.com/gs3170981/vscode_cors.git


结束语

如有bug/意见,望提Issues,如好用请star~

  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值