天天看點

ajax同源政策和解決同源政策的方法和模拟封裝jsonp函數和CORS跨域共享和服務端代理

同源政策

1.ajax請求限制

ajax隻能向自己的伺服器發送請求;

比如現在有一個A網站、有一個B網站,A網站中的 HTML 檔案隻能向A網站伺服器中發送 Ajax 請求,B網站中的 HTML 檔案隻能向 B 網站中發送 Ajax 請求,但是 A 網站是不能向 B 網站發送 Ajax請求的,同理,B 網站也不能向 A 網站發送 Ajax請求。

2.什麼是同源

如果兩個頁面擁有相同的協定、域名和端口,那麼這兩個頁面就屬于同一個源,其中隻要有一個不相同,就是不同源。

3.同源政策的目的

同源政策是為了保證使用者資訊安全,防止惡意的網站竊取資料,。最初的同源政策是指

A 網站在用戶端設定的 Cookie,B網站是不能通路的。

随着網際網路的發展,同源政策也越來越嚴格,在不同源的情況下,其中有一項規定就是無法向非同源位址發送Ajax 請求,如果請求,浏覽器就會報錯。

4.使用jsonp解決同源限制(跨域)

它不屬于 Ajax 請求,但它可以模拟 Ajax 請求。

1.将不同源的伺服器請求位址寫在script标簽的src屬性中;

2.伺服器端響應資料必須是一個函數的調用,真正要發送給用戶端的資料需要作為函數調用的參數;

const data = 'fn({name: "張三", age: "20"})';
 res.send(data);
           

3.在用戶端全局作用域下定義fn

4.在fn函數内部對伺服器端傳回的資料進行處理;

5.封裝jsonp函數

友善請求發送

function jsonp(options){
    //動态建立script标簽
    var script = document.createElement('script');
    // 拼接字元串變量
    var params = '';
    for(var attr in options.data){
        params += "&" +attr +"="+options.data[attr];
    }
    // 随機一個函數名
    var fnName = 'myJsonp'+Math.random().toString().replace('.','');
    // 把那個函數變成全局的函數
    window[fnName] = options.success;
    //為script标簽添加src屬性
    script.src = options.url+'?callback=' + fnName+params;
    //将script标簽追加到頁面中
    document.body.appendChild(script);
    // 為script添加onload事件
    script.onload = function(){
        document.body.removeChild(script);

    }
}
           

案例 擷取騰訊網天氣資訊

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>使用jsonp擷取騰訊天氣資訊</title>
    <link rel="stylesheet" href="/assets/bootstrap/dist/css/bootstrap.min.css">
    <style>
        .container {
            padding-top: 60px;
        }
    </style>
</head>

<body>
    <div class="container">
        <table class="table table-striped table-hover" align="center" id="box"> </table>

    </div>
    <script src="/js/jsonp.js"></script>
    <script src="./js/template-web.js"></script>
    <script type="text/html" id="tpl">
        <tr>
            <th>時間</th>
            <th>溫度</th>
            <th>天氣</th>
            <th>風向</th>
            <th>風力</th>
        </tr>
        {{each info}}
        <tr>
            <td>{{dateFormat($value.update_time)}}</td>
            <td>{{$value.degree}}</td>
            <td>{{$value.weather}}</td>
            <td>{{$value.wind_direction}}</td>
            <td>{{$value.wind_power}}</td>
        </tr>
        {{/each}}
    
    </script>
    <script>
        //擷取table标簽
        var box = document.getElementById('box');
		//封裝函數,把變量開放到模闆中,設定時間格式
        function dateFormat(date){
            var year = date.substr(0, 4);
			var month = date.substr(4, 2);
			var day = date.substr(6, 2);
			var hour = date.substr(8, 2);
			var minute = date.substr(10, 2);
            var seconds = date.substr(12, 2);
            return year+'年'+month+'月'+ day + '日' + hour + '時' + minute + '分' + seconds + '秒';
        }
        // 想模闆中開放外部變量
        template.defaults.imports.dateFormat = dateFormat;

        //向服務端擷取天氣資訊
        jsonp({
            url:'http://wis.qq.com/weather/common',
            data:{
                source:'pc',
                // weather_type:'forecast_1h|forecast_24h',
                //一天24小時天氣
                weather_type:'forecast_1h',
                province:'河南省',
                city:'鄭州市'
            },
            success:function(data){
                //傳回結果,拼接在模闆中
               var html =  template('tpl',{info:data.data.forecast_1h})
               //渲染在頁面中
                box.innerHTML = html;
            }
        })
    </script>
</body>

</html>
           

6.CORS跨域共享

CORS:全稱為 Cross-originresource sharing,即跨域資源共享,它允許浏覽器向跨域伺服器發送 Ajax 請求,克服了 Ajax 隻能同源使用的限制。

ajax同源政策和解決同源政策的方法和模拟封裝jsonp函數和CORS跨域共享和服務端代理

跨域資源共享需要在另一個伺服器設定一下配置

app.use((req, res, next) => {
	// 1.允許哪些用戶端通路我
	// * 代表允許所有的用戶端通路我
	// 注意:如果跨域請求中涉及到cookie資訊傳遞,值不可以為*号 比如是具體的域名資訊
	res.header('Access-Control-Allow-Origin', 'http://localhost:3000')
	// 2.允許用戶端使用哪些請求方法通路我
	res.header('Access-Control-Allow-Methods', 'get,post')
	// 允許用戶端發送跨域請求時攜帶cookie資訊
	res.header('Access-Control-Allow-Credentials', true);
	next();
});
           

7.服務端代了解決非同源限制

//用戶端設定
<button id="btn">發送請求</button>
    <script src="/js/ajax.js"></script>
    <script>
        //擷取按鈕
        var btn = document.getElementById('btn');
        //為按鈕添加點選事件
        btn.onclick = function(){
            ajax({
                type:'get',
                url:'http://localhost:3000/server',
                success:function(data){
                    console.log(data);                }
            })
        }
//使用端口為3000的伺服器代理通路端口為3001的本地域名
//端口為3000的伺服器配置

//導入request向其他伺服器端請求資料的子產品,傳回一個方法  ,調用這個方法就可以想起他伺服器端發送請求
//伺服器端沒有同源政策影響的,可以随意發送
const request = require('request');
app.get('/server', (req, res) => {
    request('http://localhost:3001/cross', (err, response, body) => {
     
        res.send(body);
    })
});
           

8.關于跨域一些問題

1.為什麼會有跨域--------ajax同源限制;

2.隻有浏覽器(前端)裡面有跨域,背景沒有跨域;

3.手機浏覽器,微信小程式,app(安卓,ios) 都不存在跨域;

4.jsop隻支援get請求;

5.post跨域如何解決-------CORS

6.http協定無連接配接無狀态,使用cookie進行狀态保持;

7.http攜帶cookie,跨域不會攜帶cookie;

8.如何解決跨域------1.jsonp,2.CORS,3.服務端代理,4.postMessage

繼續閱讀