What are the front-end cross-domain solutions?

青灯夜游
Release: 2023-01-05 16:13:54
Original
9552 people have browsed it

Scheme: 1. jsonp; 2. "document.domain" and iframe; 3. "location.hash" and iframe; 4. "window.name" and iframe; 5. postMessage; 6. CORS; 7. nginx proxy, etc.

What are the front-end cross-domain solutions?

What is cross-domain?

Cross-domain refers to a document or script in one domain trying to request resources in another domain. Cross-domain here is broad.

Broadly defined cross-domain:

1.) 资源跳转: A链接、重定向、表单提交
2.) 资源嵌入: <link>、<script>、<img>、<frame>等dom标签,还有样式中background:url()、@font-face()等文件外链
3.) 脚本请求: js发起的ajax请求、dom和js对象的跨域操作等
Copy after login

In fact, what we usually call cross-domain is in a narrow sense, which is a type of request scenario restricted by the browser's same-origin policy.

What is the same origin policy?

Same origin policy/SOP (Same origin policy) is a convention introduced into the browser by Netscape in 1995. It is the core and most basic security function of the browser. If the same origin policy is missing, Origin policy, browsers are vulnerable to XSS, CSFR and other attacks. The so-called same origin means that the "protocol, domain name, and port" are the same. Even if two different domain names point to the same IP address, they are not from the same origin.

The same origin policy restricts the following behaviors:

1.) Cookie、LocalStorage 和 IndexDB 无法读取
2.) DOM 和 Js对象无法获得
3.) AJAX 请求不能发送
Copy after login

Common cross-domain scenarios

URL                                      说明                    是否允许通信
http://www.domain.com/a.js
http://www.domain.com/b.js         同一域名,不同文件或路径           允许
http://www.domain.com/lab/c.js

http://www.domain.com:8000/a.js
http://www.domain.com/b.js         同一域名,不同端口                不允许
 
http://www.domain.com/a.js
https://www.domain.com/b.js        同一域名,不同协议                不允许
 
http://www.domain.com/a.js
http://192.168.4.12/b.js           域名和域名对应相同ip              不允许
 
http://www.domain.com/a.js
http://x.domain.com/b.js           主域相同,子域不同                不允许
http://domain.com/c.js
 
http://www.domain1.com/a.js
http://www.domain2.com/b.js        不同域名                         不允许
Copy after login

Cross-domain solutions

1. Cross-domain via jsonp
2. Cross-domain document.domain iframe
3. Cross-domain location.hash iframe
4. Cross-domain window.name iframe
5. Cross-domain postMessage
6. Cross-domain resource sharing (CORS)
7. nginx proxy cross-domain
8. nodejs middleware proxy cross-domain
9. WebSocket protocol cross-domain

1. Cross-domain through jsonp

Usually in order to reduce the load on the web server, we separate static resources such as js, css, img, etc. to another server with an independent domain name, and then pass them through in the html page The corresponding tag loads static resources from different domain names and is allowed by the browser. Based on this principle, we can dynamically create a script and then request a URL with parameters to achieve cross-domain communication.

1.) Native implementation:

 <script>
    var script = document.createElement(&#39;script&#39;);
    script.type = &#39;text/javascript&#39;;

    // 传参一个回调函数名给后端,方便后端返回时执行这个在前端定义的回调函数
    script.src = &#39;http://www.domain2.com:8080/login?user=admin&callback=handleCallback&#39;;
    document.head.appendChild(script);

    // 回调执行函数
    function handleCallback(res) {
        alert(JSON.stringify(res));
    }
 </script>
Copy after login

The server returns as follows (the global function is executed when returning):

handleCallback({"status": true, "user": "admin"})
Copy after login

2.) jquery ajax:

$.ajax({
    url: &#39;http://www.domain2.com:8080/login&#39;,
    type: &#39;get&#39;,
    dataType: &#39;jsonp&#39;,  // 请求方式为jsonp
    jsonpCallback: "handleCallback",    // 自定义回调函数名
    data: {}
});
Copy after login

3.) vue.js:

this.$http.jsonp(&#39;http://www.domain2.com:8080/login&#39;, {
    params: {},
    jsonp: &#39;handleCallback&#39;
}).then((res) => {
    console.log(res); 
})
Copy after login

Back-end node.js code example:

var querystring = require(&#39;querystring&#39;);
var http = require(&#39;http&#39;);
var server = http.createServer();

server.on(&#39;request&#39;, function(req, res) {
    var params = qs.parse(req.url.split(&#39;?&#39;)[1]);
    var fn = params.callback;

    // jsonp返回设置
    res.writeHead(200, { &#39;Content-Type&#39;: &#39;text/javascript&#39; });
    res.write(fn + &#39;(&#39; + JSON.stringify(params) + &#39;)&#39;);

    res.end();
});

server.listen(&#39;8080&#39;);
console.log(&#39;Server is running at port 8080...&#39;);
Copy after login

jsonp Disadvantages: Only one kind of get request can be implemented.

2. document.domain iframe cross-domain

This solution is limited to cross-domain application scenarios where the main domain is the same but the subdomains are different.

Implementation principle: Both pages forcefully set document.domain as the basic main domain through js, thus achieving the same domain.

1.) Parent window: (http://www.domain.com/a.html)

<iframe id="iframe" src="http://child.domain.com/b.html"></iframe>
<script>
    document.domain = &#39;domain.com&#39;;
    var user = &#39;admin&#39;;
</script>
Copy after login

2.) Child window: (http://child.domain.com /b.html)

<script>
    document.domain = &#39;domain.com&#39;;
    // 获取父窗口中变量
    alert(&#39;get js data from parent ---> &#39; + window.parent.user);
</script>
Copy after login

3. location.hash iframe cross-domain

Implementation principle: a wants to communicate with b across domains, through the intermediate page c . For three pages, the location.hash of iframe is used to transfer values ​​between different domains, and direct js access is used to communicate between the same domains.

Specific implementation: A domain: a.html -> B domain: b.html -> A domain: c.html, different domains a and b can only communicate one-way through hash values, b and c is also in a different domain and can only communicate in one direction, but c and a are in the same domain, so c can access all objects on the a page through parent.parent.

1.) 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(&#39;iframe&#39;);

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

2.) b.html: (http://www.domain2 .com/b.html)

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

3.) c.html: (http://www.domain1.com/c.html)

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

4. window. name iframe cross-domain

The uniqueness of the window.name attribute: the name value still exists after loading different pages (even different domain names), and can support very long name values ​​​​(2MB).

1.) a.html: (http://www.domain1.com/a.html)

var proxy = function(url, callback) {
    var state = 0;
    var iframe = document.createElement(&#39;iframe&#39;);

    // 加载跨域页面
    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 = &#39;http://www.domain1.com/proxy.html&#39;;
            state = 1;
        }
    };

    document.body.appendChild(iframe);

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

// 请求跨域b页面数据
proxy(&#39;http://www.domain2.com/b.html&#39;, function(data){
    alert(data);
});
Copy after login

2.) proxy.html: (http://www.domain1 .com/proxy....
Intermediate proxy page, in the same domain as a.html, the content can be empty.

3.) b.html: (http://www.domain2. com/b.html)

<script>
    window.name = &#39;This is domain2 data!&#39;;
</script>
Copy after login

Summary: The src attribute of the iframe is transferred from the external domain to the local domain, and the cross-domain data is passed from the external domain to the local domain by the window.name of the iframe. This cleverly bypasses the browser's cross-domain access restrictions, but at the same time it is a safe operation.

5. postMessage cross-domain

postMessage is an API in HTML5 XMLHttpRequest Level 2, and is one of the few window attributes that can be operated across domains. It is available To solve the following problems:
a.) Data transfer between the page and its opened new window
b.) Message transfer between multiple windows
c.) Message transfer between the page and nested iframe
d.) Cross-domain data transfer in the above three scenarios

Usage: postMessage(data, origin) method accepts two parameters
data: The html5 specification supports any basic type or copyable object, However, some browsers only support strings, so it is best to use JSON.stringify() serialization when passing parameters.
origin: Protocol host port number, it can also be set to "*", which means it can be passed to any window. If you want to specify the same origin as the current window, set it to "/".

1.) 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(&#39;iframe&#39;);
    iframe.onload = function() {
        var data = {
            name: &#39;aym&#39;
        };
        // 向domain2传送跨域数据
        iframe.contentWindow.postMessage(JSON.stringify(data), &#39;http://www.domain2.com&#39;);
    };

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

2.) b.html: (http://www.domain2 .com/b.html)

<script>
    // 接收domain1的数据
    window.addEventListener(&#39;message&#39;, function(e) {
        alert(&#39;data from domain1 ---> &#39; + e.data);

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

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

六、 跨域资源共享(CORS)

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

需注意的是:由于同源策略的限制,所读取的cookie为跨域请求接口所在域的cookie,而非当前页。如果想实现当前页cookie的写入,可参考下文:七、nginx反向代理中设置proxy_cookie_domain 和 八、NodeJs中间件代理中cookieDomainRewrite参数的设置。

目前,所有浏览器都支持该功能(IE8+:IE8/9需要使用XDomainRequest对象来支持CORS)),CORS也已经成为主流的跨域解决方案。

1、 前端设置:

1.)原生ajax

// 前端设置是否带cookie
xhr.withCredentials = true;
Copy after login

示例代码:

var xhr = new XMLHttpRequest(); // IE8/9需用window.XDomainRequest兼容

// 前端设置是否带cookie
xhr.withCredentials = true;

xhr.open(&#39;post&#39;, &#39;http://www.domain2.com:8080/login&#39;, true);
xhr.setRequestHeader(&#39;Content-Type&#39;, &#39;application/x-www-form-urlencoded&#39;);
xhr.send(&#39;user=admin&#39;);

xhr.onreadystatechange = function() {
    if (xhr.readyState == 4 && xhr.status == 200) {
        alert(xhr.responseText);
    }
};
Copy after login

2.)jQuery ajax

$.ajax({
    ...
   xhrFields: {
       withCredentials: true    // 前端设置是否带cookie
   },
   crossDomain: true,   // 会让请求头中包含跨域的额外信息,但不会含cookie
    ...
});
Copy after login

3.)vue框架

a.) axios设置:

axios.defaults.withCredentials = true
Copy after login

b.) vue-resource设置:

Vue.http.options.credentials = true
Copy after login
2、 服务端设置:

若后端设置成功,前端浏览器控制台则不会出现跨域报错信息,反之,说明没设成功。

1.)Java后台:

/*
 * 导入包:import javax.servlet.http.HttpServletResponse;
 * 接口参数中定义:HttpServletResponse response
 */

// 允许跨域访问的域名:若有端口需写全(协议+域名+端口),若没有端口末尾不用加&#39;/&#39;
response.setHeader("Access-Control-Allow-Origin", "http://www.domain1.com"); 

// 允许前端带认证cookie:启用此项后,上面的域名不能为&#39;*&#39;,必须指定具体的域名,否则浏览器会提示
response.setHeader("Access-Control-Allow-Credentials", "true"); 

// 提示OPTIONS预检时,后端需要设置的两个常用自定义头
response.setHeader("Access-Control-Allow-Headers", "Content-Type,X-Requested-With");
Copy after login

2.)Nodejs后台示例:

var http = require(&#39;http&#39;);
var server = http.createServer();
var qs = require(&#39;querystring&#39;);

server.on(&#39;request&#39;, function(req, res) {
    var postData = &#39;&#39;;

    // 数据块接收中
    req.addListener(&#39;data&#39;, function(chunk) {
        postData += chunk;
    });

    // 数据接收完毕
    req.addListener(&#39;end&#39;, function() {
        postData = qs.parse(postData);

        // 跨域后台设置
        res.writeHead(200, {
            &#39;Access-Control-Allow-Credentials&#39;: &#39;true&#39;,     // 后端允许发送Cookie
            &#39;Access-Control-Allow-Origin&#39;: &#39;http://www.domain1.com&#39;,    // 允许访问的域(协议+域名+端口)
            /* 
             * 此处设置的cookie还是domain2的而非domain1,因为后端也不能跨域写cookie(nginx反向代理可以实现),
             * 但只要domain2中写入一次cookie认证,后面的跨域接口都能从domain2中获取cookie,从而实现所有的接口都能跨域访问
             */
            &#39;Set-Cookie&#39;: &#39;l=a123456;Path=/;Domain=www.domain2.com;HttpOnly&#39;  // HttpOnly的作用是让js无法读取cookie
        });

        res.write(JSON.stringify(postData));
        res.end();
    });
});

server.listen(&#39;8080&#39;);
console.log(&#39;Server is running at port 8080...&#39;);
Copy after login

七、 nginx代理跨域

1、 nginx配置解决iconfont跨域

浏览器跨域访问js、css、img等常规静态资源被同源策略许可,但iconfont字体文件(eot|otf|ttf|woff|svg)例外,此时可在nginx的静态资源服务器中加入以下配置。

location / {
  add_header Access-Control-Allow-Origin *;
}
Copy after login
2、 nginx反向代理接口跨域

跨域原理: 同源策略是浏览器的安全策略,不是HTTP协议的一部分。服务器端调用HTTP接口只是使用HTTP协议,不会执行JS脚本,不需要同源策略,也就不存在跨越问题。

实现思路:通过nginx配置一个代理服务器(域名与domain1相同,端口不同)做跳板机,反向代理访问domain2接口,并且可以顺便修改cookie中domain信息,方便当前域cookie写入,实现跨域登录。

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;
    }
}
Copy after login

1.) 前端代码示例:

var xhr = new XMLHttpRequest();

// 前端开关:浏览器是否读写cookie
xhr.withCredentials = true;

// 访问nginx中的代理服务器
xhr.open(&#39;get&#39;, &#39;http://www.domain1.com:81/?user=admin&#39;, true);
xhr.send();
Copy after login

2.) Nodejs后台示例:

var http = require(&#39;http&#39;);
var server = http.createServer();
var qs = require(&#39;querystring&#39;);

server.on(&#39;request&#39;, function(req, res) {
    var params = qs.parse(req.url.substring(2));

    // 向前台写cookie
    res.writeHead(200, {
        &#39;Set-Cookie&#39;: &#39;l=a123456;Path=/;Domain=www.domain2.com;HttpOnly&#39;   // HttpOnly:脚本无法读取
    });

    res.write(JSON.stringify(params));
    res.end();
});

server.listen(&#39;8080&#39;);
console.log(&#39;Server is running at port 8080...&#39;);
Copy after login

八、 Nodejs中间件代理跨域

node中间件实现跨域代理,原理大致与nginx相同,都是通过启一个代理服务器,实现数据的转发,也可以通过设置cookieDomainRewrite参数修改响应头中cookie中域名,实现当前域的cookie写入,方便接口登录认证。

1、 非vue框架的跨域(2次跨域)

利用node + express + http-proxy-middleware搭建一个proxy服务器。

1.)前端代码示例:

var xhr = new XMLHttpRequest();

// 前端开关:浏览器是否读写cookie
xhr.withCredentials = true;

// 访问http-proxy-middleware代理服务器
xhr.open(&#39;get&#39;, &#39;http://www.domain1.com:3000/login?user=admin&#39;, true);
xhr.send();
Copy after login

2.)中间件服务器:

var express = require(&#39;express&#39;);
var proxy = require(&#39;http-proxy-middleware&#39;);
var app = express();

app.use(&#39;/&#39;, proxy({
    // 代理跨域目标接口
    target: &#39;http://www.domain2.com:8080&#39;,
    changeOrigin: true,

    // 修改响应头信息,实现跨域并允许带cookie
    onProxyRes: function(proxyRes, req, res) {
        res.header(&#39;Access-Control-Allow-Origin&#39;, &#39;http://www.domain1.com&#39;);
        res.header(&#39;Access-Control-Allow-Credentials&#39;, &#39;true&#39;);
    },

    // 修改响应信息中的cookie域名
    cookieDomainRewrite: &#39;www.domain1.com&#39;  // 可以为false,表示不修改
}));

app.listen(3000);
console.log(&#39;Proxy server is listen at port 3000...&#39;);
Copy after login

3.)Nodejs后台同(六:nginx)

2、 vue框架的跨域(1次跨域)

利用node + webpack + webpack-dev-server代理接口跨域。在开发环境下,由于vue渲染服务和接口代理服务都是webpack-dev-server同一个,所以页面与代理接口之间不再跨域,无须设置headers跨域信息了。

webpack.config.js部分配置:

module.exports = {
    entry: {},
    module: {},
    ...
    devServer: {
        historyApiFallback: true,
        proxy: [{
            context: &#39;/login&#39;,
            target: &#39;http://www.domain2.com:8080&#39;,  // 代理跨域目标接口
            changeOrigin: true,
            secure: false,  // 当代理某些https服务报错时用
            cookieDomainRewrite: &#39;www.domain1.com&#39;  // 可以为false,表示不修改
        }],
        noInfo: true
    }
}
Copy after login

九、 WebSocket协议跨域

WebSocket protocol是HTML5一种新的协议。它实现了浏览器与服务器全双工通信,同时允许跨域通讯,是server push技术的一种很好的实现。
原生WebSocket API使用起来不太方便,我们使用Socket.io,它很好地封装了webSocket接口,提供了更简单、灵活的接口,也对不支持webSocket的浏览器提供了向下兼容。

1.)前端代码:

<p>user input:<input type="text"></p>
<script src="https://cdn.bootcss.com/socket.io/2.2.0/socket.io.js"></script>
<script>
var socket = io(&#39;http://www.domain2.com:8080&#39;);

// 连接成功处理
socket.on(&#39;connect&#39;, function() {
    // 监听服务端消息
    socket.on(&#39;message&#39;, function(msg) {
        console.log(&#39;data from server: ---> &#39; + msg); 
    });

    // 监听服务端关闭
    socket.on(&#39;disconnect&#39;, function() { 
        console.log(&#39;Server socket has closed.&#39;); 
    });
});

document.getElementsByTagName(&#39;input&#39;)[0].onblur = function() {
    socket.send(this.value);
};
</script>
Copy after login

2.)Nodejs socket后台:

var http = require(&#39;http&#39;);
var socket = require(&#39;socket.io&#39;);

// 启http服务
var server = http.createServer(function(req, res) {
    res.writeHead(200, {
        &#39;Content-type&#39;: &#39;text/html&#39;
    });
    res.end();
});

server.listen(&#39;8080&#39;);
console.log(&#39;Server is running at port 8080...&#39;);

// 监听socket连接
socket.listen(server).on(&#39;connection&#39;, function(client) {
    // 接收信息
    client.on(&#39;message&#39;, function(msg) {
        client.send(&#39;hello:&#39; + msg);
        console.log(&#39;data from client: ---> &#39; + msg);
    });

    // 断开处理
    client.on(&#39;disconnect&#39;, function() {
        console.log(&#39;Client socket has closed.&#39;); 
    });
});
Copy after login

中间件跨域postmessagenginxcors

更多编程相关知识,请访问:编程视频!!

The above is the detailed content of What are the front-end cross-domain solutions?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!