如何bypass 限制CORS 的 same-origin security policy

in cn •  7 years ago  (edited)

什么是限制 CORS 的 same-origin security policy


假设你有个网站 abc.com 里面有个javascript 做 Ajax HTTP request 到 xyz.com, by default ,你的browser 会丢一个error 叫做 No Access-Control-Allow-Origin

corserror.png

除非 xyz.com 在 回你的 http request 时, 在 http response 的header 里有放

Access-Control-Allow-Origin: *

那你就可以跨区域名到 xyz.com 做 Ajax HTTP request。

但假设 xyz.com 是别人的网站,不受你的控制,例如 binance.com 呢?

当然,你可以在 abc.com 的后端(ruby/python/php) 等等做http request 到 xyz.com,

然后你的abc.com 的 Javascript 再ajax HTTP 到自己的abc.com 拿 json .

但是假设你的网站是没有后端的情况呢, 例如那些host 在 github 的gh-pages呢 , 只有那些 static resources (html,css,js )

这时你就可以用一个代理后端的网站, 例如

https://cors-anywhere.herokuapp.com/

Cors-anywhere 帮你加 Access-Control-Allow-Origin: * 到 http 的 response header里


如何使用 Cors-anywhere

非常简单, 假设你本来要 http 到

https://www.binance.com/api/v1/ticker/allPrices

用 cors-anywhere 代理的话则是

https://cors-anywhere.herokuapp.com/https://www.binance.com/api/v1/ticker/allPrices

那就搞定了。。
以下我写了一个example 供参考

https://jsfiddle.net/vwobc4y5/

谢谢阅读。

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  

Thank you @tensaix2j for making a transfer to me for an upvote of 3.54% on this post! Half of your bid goes to @budgets which funds growth projects for Steem like our top 25 posts on Steem! The other half helps holders of Steem power earn about 60% APR on a delegation to me! For help, will you please visit https://jerrybanfield.com/contact/ because I check my discord server daily? To learn more about Steem, will you please use http://steem.guide/ because this URL forwards to my most recently updated complete Steem tutorial?