HTML——解决跨域

1. 跨域

跨域是指一个域下的文档或脚本试图去请求另一个域下的资源,这里跨域是广义的

2. 解决跨域的方式

1.通过jsonp跨域
2.document.domain + iframe跨域
3.location.hash + iframe
4.window.name + iframe跨域
5.postMessage跨域
6.跨域资源共享(CORS)
7.nginx代理跨域
8.nodejs中间件代理跨域
9.WebSocket协议跨域

2.1. 通过jsonp跨域

jsonp缺点:只能实现get一种请求。

//jquery Ajax
$.ajax({
    url: 'http://www.domain2.com:8080/login',
    type: 'get',
    dataType: 'jsonp',  // 请求方式为jsonp
    jsonpCallback: "handleCallback",    // 自定义回调函数名
    data: {}
});
//Vue
this.$http.jsonp('http://www.domain2.com:8080/login', {
    params: {},
    jsonp: 'handleCallback'
}).then((res) => {
    console.log(res); 
})

2.2. document.domain + iframe跨域

1.此方案仅限主域相同,子域不同的跨域应用场景
2.实现原理:两个页面都通过js强制设置document.domain为基础主域,就实现了同域

<iframe id="iframe" src="http://child.domain.com/b.html"></iframe>
<script>
    document.domain = 'domain.com';
    var user = 'admin';
</script>

2.3. location.hash + iframe跨域

1.实现原理: a欲与b跨域相互通信,通过中间页c来实现。 三个页面,不同域之间利用iframe的location.hash传值,相同域之间直接js访问来通信
2.具体实现:A域:a.html -> B域:b.html -> A域:c.html,a与b不同域只能通过hash值单向通信,b与c也不同域也只能单向通信,但c与a同域,所以c可通过parent.parent访问a页面所有对象

//a.html:(http://www.domain1.com/a.html)
<iframe id="iframe" src="http://www.domain2.com/b.html" style="display:none;"></iframe>
<script>
    var iframe = document.getElementById('iframe');

    // 向b.html传hash值
    setTimeout(function() {
        iframe.src = iframe.src + '#user=admin';
    }, 1000);
    
    // 开放给同域c.html的回调方法
    function onCallback(res) {
        alert('data from c.html ---> ' + res);
    }
</script>


//b.html:(http://www.domain2.com/b.html)
<iframe id="iframe" src="http://www.domain1.com/c.html" style="display:none;"></iframe>
<script>
    var iframe = document.getElementById('iframe');

    // 监听a.html传来的hash值,再传给c.html
    window.onhashchange = function () {
        iframe.src = iframe.src + location.hash;
    };
</script>


//c.html:(http://www.domain1.com/c.html)
<script>
    // 监听b.html传来的hash值
    window.onhashchange = function () {
        // 再通过操作同域a.html的js回调,将结果传回
        window.parent.parent.onCallback('hello: ' + location.hash.replace('#user=', ''));
    };
</script>

2.4. window.name + iframe跨域

//a.html:(http://www.domain1.com/a.html)
var proxy = function(url, callback) {
    var state = 0;
    var iframe = document.createElement('iframe');

    // 加载跨域页面
    iframe.src = url;

    // onload事件会触发2次,第1次加载跨域页,并留存数据于window.name
    iframe.onload = function() {
        if (state === 1) {
            // 第2次onload(同域proxy页)成功后,读取同域window.name中数据
            callback(iframe.contentWindow.name);
            destoryFrame();

        } else if (state === 0) {
            // 第1次onload(跨域页)成功后,切换到同域代理页面
            iframe.contentWindow.location = 'http://www.domain1.com/proxy.html';
            state = 1;
        }
    };

    document.body.appendChild(iframe);

    // 获取数据以后销毁这个iframe,释放内存;这也保证了安全(不被其他域frame js访问)
    function destoryFrame() {
        iframe.contentWindow.document.write('');
        iframe.contentWindow.close();
        document.body.removeChild(iframe);
    }
};

// 请求跨域b页面数据
proxy('http://www.domain2.com/b.html', function(data){
    alert(data);
});


//proxy.html:(http://www.domain1.com/proxy.html)
中间代理页,与a.html同域,内容为空即可
//b.html:(http://www.domain2.com/b.html)
<script>
    window.name = 'This is domain2 data!';
</script>

2.5. postMessage跨域

//a.html:(http://www.domain1.com/a.html)
<iframe id="iframe" src="http://www.domain2.com/b.html" style="display:none;"></iframe>
<script>       
    var iframe = document.getElementById('iframe');
    iframe.onload = function() {
        var data = {
            name: 'aym'
        };
        // 向domain2传送跨域数据
        iframe.contentWindow.postMessage(JSON.stringify(data), 'http://www.domain2.com');
    };

    // 接受domain2返回数据
    window.addEventListener('message', function(e) {
        alert('data from domain2 ---> ' + e.data);
    }, false);
</script>



//b.html:(http://www.domain2.com/b.html)
<script>
    // 接收domain1的数据
    window.addEventListener('message', function(e) {
        alert('data from domain1 ---> ' + e.data);

        var data = JSON.parse(e.data);
        if (data) {
            data.number = 16;

            // 处理后再发回domain1
            window.parent.postMessage(JSON.stringify(data), 'http://www.domain1.com');
        }
    }, false);
</script>

2.6. 跨域资源共享(CORS)

普通跨域请求:只服务端设置Access-Control-Allow-Origin即可,前端无须设置,若要带cookie请求:前后端都需要设置。

2.7. nginx代理跨域

nginx配置解决iconfont跨域

location / {
  add_header Access-Control-Allow-Origin *;
}

nginx反向代理接口跨域

#proxy服务器
server {
    listen       81;
    server_name  www.domain1.com;

    location / {
        proxy_pass   http://www.domain2.com:8080;  #反向代理
        proxy_cookie_domain www.domain2.com www.domain1.com; #修改cookie里域名
        index  index.html index.htm;

        # 当用webpack-dev-server等中间件代理接口访问nignx时,此时无浏览器参与,故没有同源限制,下面的跨域配置可不启用
        add_header Access-Control-Allow-Origin http://www.domain1.com;  #当前端只跨域不带cookie时,可为*
        add_header Access-Control-Allow-Credentials true;
    }
}

2.8. WebSocket协议跨域

WebSocket protocol是HTML5一种新的协议。它实现了浏览器与服务器全双工通信,同时允许跨域通讯,是server push技术的一种很好的实现。

### HTML 页面问题解决方案 #### CORS (Cross-Origin Resource Sharing) CORS 是一种基于 HTTP 头的机制,允许服务器声明哪些来源可以访问资源。当客户端发起请求时,浏览器会自动添加 Origin 请求头来告知目标名来自哪个源。如果服务器同意该请求,则会在响应头部加入 `Access-Control-Allow-Origin` 字段[^1]。 对于简单请求(如 GET 或 POST),只需设置上述字段即可实现资源共享;而对于复杂请求(例如带有自定义首部或使用 PUT/DELETE 方法的情况),则需先发送预检 OPTIONS 请求给服务端验证权限后再执行实际操作[^2]。 ```javascript // 客户端 JavaScript 发起 AJAX 请求的例子 fetch('https://api.example.com/data', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ key: value }) }) .then(response => response.json()) .catch(error => console.error('Error:', error)); ``` #### JSONP (JSON with Padding) 由于早期浏览器的安全限制不允许直接通过 XMLHttpRequest 进行站调用,因此出现了利用 `<script>` 标签加载远程 JS 文件并回调函数的方式——即 JSONP 技术。这种方式仅适用于 GET 请求,并且依赖于对方 API 支持返回特定格式的数据[^3]。 不过值得注意的是,在现代 Web 开发中应谨慎考虑是否要采用此方式,因为这可能带来潜在的安全隐患,比如 XSS 攻击等风险。 ```html <!-- HTML 中嵌入 JSONP 请求 --> <script> function handleResponse(data){ document.getElementById("result").innerHTML = data.message; } </script> <script src="http://example.com/api?callback=handleResponse"></script> <div id="result">Loading...</div> ``` #### 配置代理服务器 另一种常见的做法是在本地部署一个反向代理服务器(如 Nginx),它能够接收来自前端应用程序的所有网络请求并将它们转发到真正的后端接口上。这样做的好处是可以绕过同源策略的同时保持前后端分离架构不变。 以 Nginx 为例: ```nginx server { listen 80; server_name localhost; location /api/ { proxy_pass http://backend_server_address/; # 更多配置... } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值