天天看點

Ajax基礎:CORS跨域

CORS,跨域資源共享,允許浏覽器向伺服器發送Ajax請求,克服Ajax隻能同源使用的限制

操作:

        服務端配置響應頭,用戶端繼續使用ajax,用戶端不需要做出調整

       1、允許哪些用戶端通路我(*表示所有): 

             res.header('Access-Control-Allow-Origin', '*')

        2、允許用戶端使用哪些請求方法通路我:

              res.header('Access-Control-Allow-Methods', 'get,post');

        端口3000的用戶端去通路3001,需要3001給這個請求去開門,放它進來,以實作通路

端口3000下的用戶端html代碼:

<body>
    <button id="btn">送出請求</button>
    <!-- 引入了ajax.js(封裝好的ajax函數)-->
    <script src="js/ajax.js"></script>
    <script>
        var btn = document.getElementById('btn');
        btn.onclick = function() {
            // 調用ajax去向端口3001下的路由cors發送請求
            ajax({
                type: 'get',
                url: 'http://localhost:3001/cors',
                success: function(data) {
                    alert(data);
                }
            })
        }
    </script>
</body>
           

端口3001下服務端代碼:

const express = require('express');
const corspp = express();

corspp.get('/cors', (req, res) => {
    // 允許哪些用戶端通路我(*表示所有)
    res.header('Access-Control-Allow-Origin', '*')
    // 允許用戶端使用哪些請求方法通路我
    res.header('Access-Control-Allow-Methods', 'get,post');
    // 用于cors測試
    res.send('來自3001的回應:哈喽,我的兄弟3000');
})

corspp.listen(3001);
console.log('3001已啟動');
           
Ajax基礎:CORS跨域

當我們将服務端的響應頭由原來的 * 更改為 3002 端口後

res.header('Access-Control-Allow-Origin', 'http://localhost:3002');
           

3000的用戶端将無法通路

Ajax基礎:CORS跨域

【備注】:

        如果對所有的路由的所有請求方式都要執行這樣的配置的話,那麼考慮低耦合高内聚,我們可以借助中間件,use攔截所有。

corspp.use((req, res) => {

    res.header('Access-Control-Allow-Origin', 'http://localhost:3002');

    res.header('Access-Control-Allow-Methods', 'get,post');

    res.send('來自3001的回應:哈喽,我的兄弟3000');
})
           

繼續閱讀