解決跨域的方式不下 7 8 種,相似的文章我也發表過,但開發路上總會遇到一些奇奇怪怪的限制,讓你始終無法 easy 調試,此次我乾脆寫了個 vscode 擴展,伴隨開發工具一塊兒完滅Access-Control-Allow-Originios
vscode 擴展應用商店搜索「cors」下載便可git
右下角會顯示新的 icon,點擊他便可開啓內置服務github
至此開啓了本地端口 1337 的監聽借用 lofter 的 API 嘗試web
$.ajax({
type: "get",
url: "http://www.lofter.com/trade/reward/isOpen",
success: function(res) {
console.log(res);
}
});
複製代碼
當前請求會報跨域錯誤,將以上轉換爲ajax
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);
}
});
複製代碼
返回成功json
借用 juejin 的 API 嘗試axios
$.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);
}
});
複製代碼
當前請求會報跨域錯誤,將以上轉換爲segmentfault
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);
}
});
複製代碼
返回成功api
由於設計的很是簡單,因此目前 API 配置僅有3 個跨域
關於 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
Lib
make:o︻そ ╆OVE▅▅▅▆▇◤(清一色天空)
lofter:zcxy-gs.lofter.com/
sf:segmentfault.com/u/mybestang…
若有 bug/意見,望提 Issues,如好用請 star~