This article brings you a detailed explanation of PHP synergy implementation (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
1. What is cross-domain
##JavaScript For security reasons, Cross-domain calls to objects from other pages are not allowed. So what is cross-domain? A simple understanding is that because of the restrictions of the JavaScript same-origin policy, js under the domain name a.com cannot operate objects under the domain name b.com or c.a.com.When any of the protocol, subdomain name, main domain name, and port number are different, they are all counted as different domains. Requesting resources from different domains is considered "cross-domain".
For example: http://www.abc.com/index.html requests http://www.efg.com/service.php.
Cross-domain does not mean that the request cannot be sent out, the request can be sent out, the server can receive the request and return the result normally, but the result is intercepted by the browser . The reason why it occurs across domains is that it is restricted by the same-origin policy. The same-origin policy requires that the source is the same for normal communication, that is, the protocol, domain name, and port number are all exactly the same.
You can refer to the picture below to help you understand cross-domain in depth.Special note on two points: First: If there are cross-domain problems caused by protocols and ports, the "front desk" is powerless. of. Second: Regarding cross-domain issues, domains are only identified by the "header of the URL" and will not be judged based on whether the IP addresses corresponding to the domain names are the same. "The header of the URL" can be understood as "the protocol, domain name and port must match".
2. What is the same-origin policy and its restrictions
The same-origin policy restricts how documents or scripts loaded from one source interact with resources from another source. . This is a critical security mechanism for isolating potentially malicious files. Its existence can protect user privacy information, prevent identity forgery, etc. (read Cookie). The content restricted by the same origin policy includes:But there are three tags that allow cross-domain loading of resources:
1.<img alt="What is cross-domain? Introduction to four ways of cross-domain JavaScript" > 2.<link> 3.<script></script>
3. Cross-domain processing method 1 - JSONP
1.JSONP principleUtilization<script># With this open policy of the ## element, web pages can obtain JSON data dynamically generated from other sources. JSONP requests must be supported by the other party's server. <code></script>2. Comparison between JSONP and AJAX
3. JSONP advantages and disadvantages
4.JSONP process (take the third-party API address as an example, there is no need to consider the background program)
<script> function fn(data) { alert(data.msg); } </script> <script></script>
fn({ msg:'this is json data'})
$.ajax({
url:"http://crossdomain.com/jsonServerResponse",
dataType:"jsonp",
type:"get",//可以省略
jsonpCallback:"fn",//->自定义传递给服务器的函数名,而不是使用jQuery自动生成的,可省略
jsonp:"jsonp",//->把传递函数名的那个形参callback变为jsonp,可省略
success:function (data){
console.log(data);}
});
整个CORS通信过程,都是浏览器自动完成,不需要用户参与。对于开发者来说,CORS通信与同源的AJAX通信没有差别,代码完全一样。浏览器一旦发现AJAX请求跨源,就会自动添加一些附加的头信息,有时还会多出一次附加的请求,但用户不会有感觉。因此,实现CORS通信的关键是服务器。只要服务器实现了CORS接口,就可以跨源通信。 CORS要求浏览器(>IE10)和服务器的同时支持,是跨域的根本解决方法,由浏览器自动完成。 例如:网站http://localhost:63342/ 页面要请求http://localhost:3000/users/userlist 页面,userlist页面返回json字符串格{name: 'Mr.Cao', gender: 'male', career: 'IT Education'} 在响应头上添加Access-Control-Allow-Origin属性,指定同源策略的地址。同源策略默认地址是网页的本身。只要浏览器检测到响应头带上了CORS,并且允许的源包括了本网站,那么就不会拦截请求响应。
五、处理跨域方法三——WebSocket Websocket是HTML5的一个持久化的协议,它实现了浏览器与服务器的全双工通信,同时也是跨域的一种解决方案。WebSocket和HTTP都是应用层协议,都基于 TCP 协议。但是 WebSocket 是一种双向通信协议,在建立连接之后,WebSocket 的 server 与 client 都能主动向对方发送或接收数据。同时,WebSocket 在建立连接时需要借助 HTTP 协议,连接建立好了之后 client 与 server 之间的双向通信就与 HTTP 无关了。 原生WebSocket API使用起来不太方便,我们使用Socket.io,它很好地封装了webSocket接口,提供了更简单、灵活的接口,也对不支持webSocket的浏览器提供了向下兼容。 六、处理跨域方法四——postMessage 如果两个网页不同源,就无法拿到对方的DOM。典型的例子是iframe窗口和window.open方法打开的窗口,它们与父窗口无法通信。HTML5为了解决这个问题,引入了一个全新的API:跨文档通信 API(Cross-document messaging)。这个API为window对象新增了一个window.postMessage方法,允许跨窗口通信,不论这两个窗口是否同源。postMessage方法的第一个参数是具体的信息内容,第二个参数是接收消息的窗口的源(origin),即"协议 + 域名 + 端口"。也可以设为*,表示不限制域名,向所有窗口发送。 接下来我们看个例子:1.CORS原理
2.CORS优缺点
优点在于功能更加强大支持各种HTTP Method,缺点是兼容性不如JSONP。
只需要在服务器端做一些小小的改造即可:header("Access-Control-Allow-Origin:*");
header("Access-Control-Allow-Methods:POST,GET");
//在服务器端设置同源策略地址
router.get("/userlist", function (req, res, next) {
var user = {name: 'Mr.Cao', gender: 'male', career: 'IT Education'};
res.writeHeader(200,{"Access-Control-Allow-Origin":'http://localhost:63342'});
res.write(JSON.stringify(user));
res.end();
});
//前端代码:
<p>user input:<input></p>
<script></script>
<script>
var socket = io('http://www.domain2.com:8080');
// 连接成功处理
socket.on('connect', function() {
// 监听服务端消息
socket.on('message', function(msg) {
console.log('data from server: ---> ' + msg);
});
// 监听服务端关闭
socket.on('disconnect', function() {
console.log('Server socket has closed.');
});
});
document.getElementsByTagName('input')[0].onblur = function() {
socket.send(this.value);
};
</script>
//Nodejs socket后台:
var http = require('http');
var socket = require('socket.io');
// 启http服务
var server = http.createServer(function(req, res) {
res.writeHead(200, {
'Content-type': 'text/html'
});
res.end();
});
server.listen('8080');
console.log('Server is running at port 8080...');
// 监听socket连接
socket.listen(server).on('connection', function(client) {
// 接收信息
client.on('message', function(msg) {
client.send('hello:' + msg);
console.log('data from client: ---> ' + msg);
});
// 断开处理
client.on('disconnect', function() {
console.log('Client socket has closed.');
});
});
http://localhost:63342/index.html页面向http://localhost:3000/message.html传递“跨域请求信息”//发送信息页面 http://localhost:63342/index.html
<meta>
<title>跨域请求</title>
<iframe></iframe>
<input>
<script>
function run(){
var frm=document.getElementById("frm");
frm.contentWindow.postMessage("跨域请求信息","http://localhost:3000");
}
</script>
//接收信息页面 http://localhost:3000/message.html
window.addEventListener("message",function(e){ //通过监听message事件,可以监听对方发送的消息。
console.log(e.data);
},false);
The above is the detailed content of What is cross-domain? Introduction to four ways of cross-domain JavaScript. For more information, please follow other related articles on the PHP Chinese website!