Handling cross-domain requests

As a front-end person, I often need to call the interface to request data from the server, but sometimes I do n’t get the data we expect, but I report an error, and Access-control-Allow-Origin appears.

The error message indicates that there is a cross-domain situation. Before solving the cross-domain problem, we must first understand why it is cross-domain.

Homology strategy

Homology means that the domain name, protocol, and port are the same. The so-called "same-origin policy" is simply based on security considerations, the current domain can not access things in other domains. So there will be cross-domain issues

Under the same-origin policy, pages under a certain server cannot obtain data outside the server. Otherwise it will produce the following situation

But neither <img>src (get picture) and <script>src (get javascript) conform to the same-origin policy, they can get data across domains. The JSONP introduced here is to use <script>src to achieve cross-domain data acquisition.

JSONP

The principle of JSONP's implementation of cross-domain requests is simply to create <script>tags dynamically , and then use <script>the src to obtain data across domains without being constrained by the same-origin policy. Just

Introduce the interface as a json file to the page, as a function call
 
JSONP consists of two parts: callback function and data. The callback function is the function that should be called on the page when the response arrives. The name of the callback function is generally specified in the request. The data is the JSON data passed into the callback function.
1 <script type = "text / javascript">
 2      // The returned JSON is passed into the callback function as a parameter to manipulate the data through the callback function 
3        function handleResponse (response) {
 4                console.log (response);
 5    }
 6    
7         window.onload = function () {
 8               var oBtn = document.getElementById ('btn' );
 9                oBtn.onclick = function () { 
 10                       // Create a <script> tag dynamically, set its src, and set the callback function in src     
11                       var script = document.createElement ("script" );
 12                       script.src = "https://xxx&callback=handleResponse";
13                       document.body.insertBefore(script, document.body.firstChild);   
14                 };
15          }
16 </script>

1. The advantage of JSONP is that it is not restricted by the same-origin policy as the Ajax request implemented by the XMLHttpRequest object; it has better compatibility and can be run in older browsers, without the support of XMLHttpRequest or ActiveX And after the request is completed, the result can be returned by calling callback.

2. The disadvantage of JSONP is that it only supports GET requests and does not support other types of HTTP requests such as POST;

3. The most basic principle of JSONP is: dynamically add a <script> tag, and the src attribute of the script tag is not limited by cross-domain. In other words, this cross-domain approach has nothing to do with the ajax XmlHttpRequest protocol.

jQuery package JSONP

            $ .ajax ({ 
                url: "https: // xxx" , 
                type: "GET" , 
                dataType: "jsonp", // Returned data type, set to JSONP 
                success: function (res) { 
                    console.log (res ); 
                } 
             });

 

$.getJSON()

Use getJSON to achieve, as long as the callback =? Parameter is added to the address, the reference code is as follows:

          $.getJSON("https://xxx&callback=?", function(data){
                console.log(data);
           });

 

HEARTS

CORS stands for Cross-Origin Resource Sharing (Cross-Origin Resource Sharing), which is how to access resources across domains as defined by the HTML5 specification.

Origin indicates the domain, which is the domain of the current page of the browser. After JavaScript initiates a request to an external domain (such as sina.com), after receiving the response, the browser first checks whether Access-Control-Allow-Origin contains this domain. If it is, the cross-domain request is successful. If it is not, then If the request fails, JavaScript will not be able to obtain any data for the response.

Assuming the local domain is my.com, the external domain is sina.com, as long as the response header Access-Control-Allow-Originis http://my.com, or yes *, this request can be successful.

The entire process of CORS is automatically completed by the browser, no need to make any settings on the front end, and there is no difference with the usual sending of ajax requests. So, the key to implementing CORS is the server. As long as the server is set up correctly Access-Control-Allow-Origin, cross-domain communication can be achieved.

Request type:

CORS is divided into simple request and non-simple request (requires pre-check request)

Meet the following is a simple request, otherwise it is not a simple request

The request method uses one of the following methods: 
GET 
HEAD 
POST 
 
Content - The value of Type is limited to one of the following three: 
text / plain 
multipart / form-data 
application / x-www-form-urlencoded

Example code, take node.js as an example

var express = require ('express' );
 var app = express ();
 var allowCrossDomain = function (req, res, next)    
  res.header (' Access-Control-Allow-Origin ',' http: // localhost: 3001 ' ); // This field indicates which source is available for cross-domain 
} 
app.use (allowCrossDomain);

In general, using CORS simple request does not require any configuration for the front end. It is the same as sending ordinary ajax requests. The configuration of CORS is completely set in the back end, and the configuration is relatively easy. Being able to use get requests is also more convenient for us to use.

 

Guess you like

Origin www.cnblogs.com/isommer/p/12735462.html