【插件】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

返回成功

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 √

Lib

  • JQ √
  • axios √

關於

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~

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