目錄
一、同源政策
二、跨域
三、兩個場景
四、實例
五、寫在最后
一、同源政策
同源政策指三個相同,協議相同、域名相同、端口相同;三者相同為同一個域,任何一個不同為非同一個域。
二、跨域
跨域指兩個不同的域之間的資源交互。
如:
http://www.leebook.com/index.html 調用 http://www.leebook.com/data.html 不跨域(協議、域名、端口都一致) http://www.leebook.com/index.html 調用 https://www.leebook.com/index.html 跨域(協議不一樣) http://www.leebook.com/index.html 調用 http://www.book.com/index.html 跨域(域名不一樣) http://www.leebook.com/index.html 調用 http://www.leebook.com:8080/index.html 跨域(端口不一樣)
三、兩個常用場景
1、場景一
http://193.112.171.122:8090/login/index.html 調用 http://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 調用 http://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="http://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: "http://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服務器上相同的端口下;這樣子就是訪問http://193.112.171.122:8080/login/index.html;此index頁面里包含http://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