Solving the problem of front-end cross-domain

Source: Internet
Author: User

1. Why cross-domain issues occur

The Web browser contains the JavaScript interpreter, which means that once the Web page is loaded, arbitrary JavaScript code can be executed on the computer. Security risks come with it, so a well-known security strategy by Netscape-the same-origin strategy-is that JavaScript scripts cannot read the contents of documents loaded from different servers.

2. Specific circumstances of the homologous strategy

A full URL address includes:

Protocol name://Domain Name: Port number/resource path

Url

Description

Whether to allow communication

Http://www.a.com/index.html

Ftp://www.a.com/detail.html

Protocol name is different

Not allowed

Http://www.a.com/index.html

Http://www.b.com/detail.html

Protocol name is the same, domain name is different

Not allowed

Http://www.a.com:8000/index.html

Http://www.a.com:3000/detail.html

Protocol name and domain name are the same, the port number is different

Not allowed

Http://www.a.com/index.html

Http://70.80.90.00/detail.html

Protocol name is the same, assuming that the IP address represents the same URL

Not allowed

Http://www.a.com/index.html

Http://www.a.com/detail.html

Same protocol name, same domain name, same port number

Allow

Summary: If the protocol name, host name, or port number is different, it is cross-domain, even if the IP address and hostname represent the same URL.

3. Several solutions to cross-domain problems

(1). Dynamically Create Script

Because the script is not affected by the same-origin policy, it uses JS dynamic loading URL to reach the cross-domain.

functionloadscript (URL, func) {varHead = Document.head | | Document.getelementbytagname (' head ') [0]; varScript = document.createelement (' script '); SCRIPT.SRC=URL; Script.onload= Script.onreadystatechange =function(){        if(! This. readyState | | This. readystate== ' Loaded ' | | This. readystate== ' Complete ') {func (); Script.onload= Script.onreadystatechange =NULL;        }        }; Head.insertbefore (script,0);} Window.baidu={sug:function(data) {Console.log (data); }}loadscript (' Http://suggestion.baidu.com/su?wd=w ',function() {console.log (' Loaded ')});

(2). Jsonp

JSON is a text-based data exchange method that stores data in the form of key-value pairs, lightweight data formats, and is suitable for Internet delivery. And JSONP is an informal transport protocol, the principle of the protocol is: the Web client through the same way as the call script, to invoke the cross-domain server on the dynamic generation of JS format files (JSON suffix, encapsulating the data required by the client), the user passed a callback parameter to the service side, The callback function is then used as the function name to wrap the JSON data when the server returns data, so that the client can use the JSON data for processing.

//jquery implements the Jsonp cross-domain approach://$. Json method:$.getjson ({' myurl?callback=? ',function(data) {//Process Data    }); //$.ajax Method:$.ajax ({type: "Get", url: "http://www.baidu.com/. ",datatype: "Jsonp", Jsonp: "Callback",//the name of the parameter used to obtain the name of the JSONP callback function, typically the default is callbackJsonpcallback: "func ()",//Custom JSONP callback function nameSuccessfunction(JSON) {console.log (JSON); }, Error:function(Err) {Console.log (err); }});

(3). PostMessage

In HTML5, the Window object adds a very useful method:

Otherwindow.postmessage (message, targetorigin);

Otherwindow: Called Window;message: The message or object being sent; Targetorigin: The source of the target, * represents any.

  

Window.addeventlistener ("message", ReceiveMessage,false);functionReceiveMessage (event) {varOrigin = Event.origin | | Event.originalEvent.origin;//for Chrome, the Origin property was in the Event.originalevent object.  if(Origin!== "http://example.org:8080")    return;

 event.source.postMessage("the data is",event.origin);
}

(4), using cors across domains

CORS (cross-origin resource sharing) is a specification of browser technology that provides a way for Web servers to get sandboxed scripts from different domains to circumvent the browser's same-origin policy, which is a modern version of Jsonp mode.

①. The client uses an absolute address

Xhr.open ("GET", "Http://blog.csdn.net/api", true);

②. Server

The server-side support for cors is mainly done by setting up Access-control-allow-origin. If the browser detects the appropriate settings, it can allow Ajax for cross-domain access.

In PHP: Just use the following code settings.

<?php

Header ("access-control-allow-origin:*");

The meaning of the above configuration is to allow any domain-initiated requests to obtain data from the current server. This allows all domain requests to be allowed to cause potential insecurity. So we should try to be targeted to restrict the source of security, such as restrictions can only be requested from the blog Park

Access-control-allow-origin:http://www.cnblogs.com

(5). Web socket (WS protocol)

var socket = new Websockt (' ws://www.baidu.com ');//http->ws; Https->wss

Socket.send (' Hello Websockt ');

Socket.onmessage = function (event) {

var data = Event.data;

}

Solving the problem of front-end cross-domain

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.