Summary of cross domain problems and Solutions

-What is cross domain?

The browser's non homology is cross domain. That is, the two pages have different protocol s or port s or host s

-Why do cross domain problems occur?

Due to the browser's homology policy, the browser will reject cross domain requests.
*Note: strictly speaking, the browser does not reject all cross domain requests. In fact, it rejects cross domain read operations. The browser's homology restriction policy is implemented as follows:

Generally, the browser allows cross origin writes, such as links and redirections;
Generally, the browser allows cross origin embedding, such as img and script tags;
Generally, the browser does not allow cross origin reads*

-Why are there cross domain requirements?

After the project is serviced, the services with different responsibilities are scattered in different projects, and the domain names of these projects are often different, but a requirement may need to correspond to multiple services. At this time, it is necessary to call the interfaces of different services, so cross domain will occur.

-Solving cross domain problems

Generally, there are three most commonly used cross domain methods: JSONP, CORS and postMessage.

1.,JSONP

Core idea: therefore, the web page requests JSON data from the server through < script >, and the server returns the data in the callback with the specified name after receiving the request. (I just said that you can't request data on different domains through XMLHttpRequest (cross origin reads). However, it is possible to introduce js script files in different domains on the page (cross origin embedding).
Implementation method (front and back end cooperation required)

<script type="text/javascript">
    function dosomething(data){
        //Processing the data obtained
    }
</script>
<script src="http://example.com/data.php?callback=dosomething"></script>
<?php
$callback = $_GET['callback'];//Get callback function name
$data = array('a','b','c');//Data to return
echo $callback.'('.json_encode($data).')';//output
?>

[advantages and disadvantages of JSONP]
Advantages: good compatibility (compatible with low version IE)
Disadvantages: 1 JSONP only supports GET requests; 2.XMLHttpRequest has a better error handling mechanism than JSONP

2,CORS

CORS is a new official scheme recommended by W3C, which enables the server to support cross domain requests of XMLHttpRequest. CORS is very convenient to implement. You only need to add some HTTP headers so that the server can declare the allowed access sources.
Generally, when using CORS, asynchronous requests are divided into simple requests and non simple requests. The difference between non simple requests is that a pre check request will be sent first.

  • [simple request]
GET
HEAD
POST- Only if POST Methodical Content-Type A value equal to one of the following is considered a simple request
       - text/plain
       - multipart/form-data
       - application/x-www-form-urlencoded

Origin: foo.example indicates that the request comes from foo exmaple.
Access control allow origin: * indicates that the resource can be accessed by any foreign domain.
[non simple request]

PUT
DELETE
CONNECT
OPTIONS
TRACE
PATCH
  • Pre request:
Access-Control-Request-Method: POST Tell the server that the actual request will be processed according to POST mode
Access-Control-Request-Headers: X-PINGOTHER   Content-Type Tell the server that the actual request will carry two custom request header fields, and the server will decide whether to be allowed or not
  • Pre request response
Access-Control-Allow-Origin: foo.example    // Identify acceptable cross domain request sources; 
Access-Control-Allow-Methods: POST, GET, OPTIONS   //Identify acceptable cross domain request methods, access control allow headers: x-pingother, content type / / identify acceptable cross domain request custom headers;  
Access-Control-Max-Age: 86400.  //Identify the effective time (seconds) of this pre request, during which no further pre request needs to be sent;
Cross domain request with HTTP Cookies and authentication information

It usually does not cross domains, but in some cases, different login statuses need to be opened, and a special flag bit of XMLHttpRequest needs to be set. For example, the following code can set the withCredentials of XMLHttpRequest to true, so that the browser can send credential information across domains.

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;

3,postMessage

window.postMessage(message,targetOrigin) method is a newly introduced feature of html5. It can be used to send messages to other window objects. No matter whether the window object belongs to the same source or different sources, IE8 +, FireFox, Chrome, Opera and other browsers have supported window The PostMessage method.

otherWindow.postMessage(message, targetOrigin, [transfer]);

Article reference https://juejin.cn/post/6844903496521613320

Keywords: Front-end

Added by luvburn on Sat, 15 Jan 2022 15:52:56 +0200