運維角度處理跨域問題
目錄
一、同源政策
二、跨域
三、兩個場景
四、實例
五、寫在最後
一、同源政策
同源政策指三個相同,協議相同、域名相同、埠相同;三者相同為同一個域,任何一個不同為非同一個域。
二、跨域
跨域指兩個不同的域之間的資源交互。
如:
http://www.leebook.com/index.html 調用 //www.leebook.com/data.html 不跨域(協議、域名、埠都一致) http://www.leebook.com/index.html 調用 //www.leebook.com/index.html 跨域(協議不一樣) http://www.leebook.com/index.html 調用 //www.book.com/index.html 跨域(域名不一樣) http://www.leebook.com/index.html 調用 //www.leebook.com:8080/index.html 跨域(埠不一樣)
三、兩個常用場景
1、場景一
http://193.112.171.122:8090/login/index.html 調用 //193.112.171.122:8080/opreation/data.html 埠不一樣,存在跨域
中間弄一層代理,通過這種代理的方式,已經不存在跨域了:
http://193.112.171.122:8090/login/index.html 調用 http://193.112.171.122:8090/opreation/data.html 代理 http://172.16.0.16:8080/operation
2、場景二
如果是在本地打開一個網頁,如:E:\data\index.html 調用 //193.112.171.122:8080/opreation/data.html 存在跨域問題;此種在交互的服務端nginx配置加上:add_header ‘Access-Control-Allow-Origin’ ‘*’; 表示接受任何域名的訪問;此時還需要看瀏覽器支不支援跨域訪問,google瀏覽器是不支援的,可使用火狐試試,或者將本地的index.html放到如場景一一樣的伺服器上。
四、實例
這裡以場景為實例,E:\data\index.html,使用瀏覽器打開這個網頁,這個網頁中包含訪問其他服務端的域名或訪問地址
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <script src="//lib.sinaapp.com/js/jquery/2.0.2/jquery-2.0.2.min.js"></script> </head> <body> <button class="btn">獲取數據</button> <script type="text/javascript"> $(function() { $(".btn").click(function() { $.ajax({ type: "get", url: "//193.112.171.122:8080/opreation/data.html", dataType:"json", success: function(data) { console.log("獲取成功"); }, error: function() { console.log("獲取失敗"); } }); }) }) </script> </body> </html>
1、直接現象
瀏覽器會報錯;服務端返回的值再瀏覽器中不會顯示

2、處理問題的兩個方法
方法一:
在nginx端加配置 add_header ‘Access-Control-Allow-Origin’ ‘*’;此方法還存在瀏覽器是否允許跨域的問題,比如google瀏覽器即使nginx服務端加了跨域的配置,也不生效;可以使用其他的瀏覽器如火狐,或者安裝google瀏覽器的相關插件允許跨域
location /opreation { alias /leebook; add_header 'Access-Control-Allow-Origin' '*'; default_type application/json; return 200 '{"status":"success","result":"This is the nginx response"}'; }
方法二:
把放在E:\test\index.html的這個html放在與此html頁面指向的web伺服器上相同的埠下;這樣子就是訪問//193.112.171.122:8080/login/index.html;此index頁面里包含//193.112.171.122:8080/opreation/data.html ;這樣相同的IP、相同的埠、相同的協議 這樣就不存在跨域的問題。
location /login { alias /login; } location /opreation { alias /leebook; add_header 'Access-Control-Allow-Origin' '*'; default_type application/json; return 200 '{"status":"success","result":"This is the nginx response"}'; }
五、寫在最後
在平凡中堅持前行,總有一天會遇見不一樣的自己。
寫部落格記錄、思考、總結,趟過的坑不趟第二遍。
所有的文章,皆同步在公眾號「運維汪」,可關注;也可加入「不扯淡,專註於技術」的QQ群:753512236