Cross-domain request summary

Cross-domain requests, as the name suggests, are requests for content that are not in the same domain name. Due to browser security policies, such requests will most likely be rejected. So, how do we avoid request failures due to cross-origin?

1.jsonp

This is a cross-domain solution that only applies to the get request method. We know that the JavaScript script tag does not allow cross-domain requests. jsonp uses this attribute to implement content that is not in the same domain name. requested.

This method is described in jQuery as follows: If the acquired data files are stored on a remote server (with different domain names, that is, cross-domain acquisition of data), you need to use the jsonp type. Using this type creates a query string parameter callback=? which is appended to the requested URL. The server side should prefix the JSON data with the callback function name in order to complete a valid JSONP request. It means that the remote server needs to process the returned data. According to the callback parameters submitted by the client, it returns a callback (json) data, and the client will process the returned data in the way of script to do the json data. deal with. JQuery.getJSON also supports jsonp data method calls.

eg:

   Example of calling code of client JQuery.ajax:

$.ajax({
	type : "get",
	async:false,
	url : "http://www.xxx.com/ajax.do",
	dataType : "jsonp",
	jsonp: "callbackparam",//The parameter used by the server to receive the function name of the callback call
	jsonpCallback:"success_jsonpCallback",//callback的function名称
	success : function(json){
		alert(json);
		alert(json[0].name);
	},
	error:function(){
		alert('fail');
	}
});

    Example code of the server returning data:

public void ProcessRequest (HttpContext context) {
	context.Response.ContentType = "text/plain";
	String callbackFunName = context.Request["callbackparam"];
	context.Response.Write(callbackFunName + "([ { name:\"John\"}])");
}

2. Proxy

This can also be said to be server cross-domain, that is, the background goes to the cross-domain, and then the content is transmitted from the server to the front-end in the same domain. This is to solve the cross-domain request problem by bypassing the front-end browser.

3.CORS

Cross-Origin Resource Sharing (Cross-Origin Resource Sharing) is a mechanism that allows resources of the current domain (origin) (such as html/js/web service) to be accessed by scripts of other domains (origin). This is an implementation in modern browsers.

eg:

Access-Control-Allow-Origin:*;//Allow all origins to access

Access-Control-Allow-Method:POST,GET;//The way to allow access

Front-end code:

//http://127.0.0.1:8888/cors.html
var xhr = new XMLHttpRequest();
xhr.onload = function(data){
  var _data = JSON.parse(data.target.responseText)
  for(key in _data){
    console.log('key: ' + key +' value: ' + _data[key]);
  }
};
xhr.open('POST','http://127.0.0.1:2333/cors',true);
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send();

Backend code:

//http://127.0.0.1:2333/cors
app.post('/cors',(req,res) => {
  if(req.headers.origin){
    res.writeHead(200,{
      "Content-Type": "text/html; charset=UTF-8",
      "Access-Control-Allow-Origin":'http://127.0.0.1:8888'
    });
    let people = {
      type: 'hearts',
      name : 'weapon-x'
    }
    res.end(JSON.stringify(people));
  }
})

4.CSST

A scheme for transferring text across domains with CSS. It is more secure than JSONP and does not require cross-site scripting.

Link: csst

5.postmessage cross domain

The postMessage method has been added in HTML5. PostMessage can realize Cross Document Messaging. Internet Explorer 8, Firefox 3, Opera 9, Chrome 3 and Safari 4 all support postMessage.
This method can monitor the content of the cross-document message transmission by binding the message event of the window.
The principle of using postMessage to achieve cross-domain is similar to jsonp, dynamically inserting iframe tags, and then getting data back from the iframe

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324573905&siteId=291194637