The same origin policy is a security policy for browsers. First, the same domain name, protocol, and port are the same, which is mainly reflected in urls. For example, http://www.baidu.com and https://www.baidu.com are from different sources because they use different HTTP protocols. Client scripts from different sources cannot read or write to each other’s resources without explicit authorization. Now let’s look at all of the possible different sources

The same origin policy restricts the following behaviors:

  • Cookie, LocalStorage, and IndexDB cannot be read
  • DOM not available
  • Invalid AJAX request (can be requested, but browser rejects response)

Cross domain access

Cross-domain access is to overcome the restriction of the same Origin policy. Generally, cross-domain access can be implemented in the following four ways

JSONP

JSONP is an acronym for JSON with padding. JSONP is a browser BUG that uses script tags to request resources that are not subject to the same origin policy to retrieve server data

The SCR attribute of the script is used to set the location of the resource to be accessed, but in order to receive the resource with the callback function, SRC adds a callback attribute to tell the server to retrieve the data through the callback function, for example: < script SRC = “http://127.0.0.1/getNews? Callback =showNews”> callback= 127.0.0.1/getNews The server should then have a corresponding interface to handle the GET request, and transfer the data by writing the JS code to the returned body, like this:

	data = {name:"John"}// The data object to return
	dataString = JSON.stringify(data);// Change to a string
	ctx.body = ctx.query.callback + "(" + dataString + ")"
	// Set the body to return the contents of the showNews(data).
Copy the code

Then when the script tag requests the server, the server returns a string like this: ShowNews ({“name”:”John”}), which is returned to script, so script will load the string as js code into the local web page, right? So if your local code has a function showNews, then script will request the resource, This function acts as a callback function that is automatically called and receives incoming arguments.

So finally we can sum up the main technical points of the json, first is to use the script tag is not restricted by the same origin policy to request the background, and then the background by setting a js calling code and add the data you need to string is returned to the front, and then the front by the corresponding callback function to receive the returned data, The cross-domain access is now complete. However, we usually request data dynamically, rather than request all data at the beginning, so we also need to create script tags dynamically, which can be encapsulated into a JSONP function, as follows

// Front-end code
function jsonp(url,callback){// Encapsulate JSONP
	var scriptNode=document.createElement("script")
    scriptNode.setAttribute("type"."text/javascript")
    scriptNode.setAttribute("src".`${url}? callback=${callback}`)
    document.head.appendChild(scriptNode)
}

function getRes(res){// The callback function
	console.log(res)
}

// background code
function handleResquest(){
	/ /...
	var data=[{"a":1."b":2}]
	var cb=req.query.callback;
	if(cb){
	    res.send(`${cb}(JSON.stringify(${data})) `)}else{
	    res.send(`${data}`)}}// When the front-end wants to request data, it calls jSONp
jsonp("http://127.0.0.1:7001/getdata"."getRes")


Copy the code

CORS

Crossing-Origin Resource Shargin cross-domain Resource sharing, which allows browsers to send XMLHttpRequest requests to cross-source servers, overcomes the rule that AJAX can only be used in the same source.

Currently, all browsers support CORS, and servers need to implement the CORS interface. Once both sides support CORS, cross-source communication can take place. Browsers currently classify CORS requests into two categories: simple and non-simple, and we’ll focus on simple requests here.

A simple request is one that meets both of the following conditions:

  • Is one of the get, POST, and HEAD request methods
  • The HTTP header does not exceed the following fields: Accept, Accept-language, Content-language, last-Event-ID, and Content-Type

Anything that does not meet these conditions is a non-simple request

A simple request

Here is a brief description of the simple request process. First of all, when the browser finds that the AJAX cross-source request is a simple request, it automatically adds an Origin field in the header. This field is used to indicate which source (protocol + domain name + port) the request comes from, which is to attach a URL. It then passes to the server, which decides whether to approve the request based on the Origin field

If the Origin field value is not within the permitted range, the server will return a normal HTTP response, and the browser will catch the error in the XMLHttpRequest callback if it finds that the response does not have the Access-Control-Allow-Origin field.

If Origin specifies a domain name within the licensed range, the server returns a response with several additional header fields

  • Access-Control-Allow-Origin: api.bob.com

If the value is *, it means to receive requests from any domain

  • Access-Control-Allow-Credentials: true

Optional, Boolean value that indicates whether cookies are allowed to be sent, but cookies are generally not included in CORS requests by default, so set this value to true

  • Access-Control-Expose-Headers: FooBar

Optional. In CORS requests, the getResponseHeader() method of the XMLHttpRequest object takes only six basic fields: Cache-control, Content-language, Content-Type, Expires, Last-Modified, Pragma. If you want to get other fields, you must specify access-Control-expose-headers. The above example specifies that getResponseHeader(‘FooBar’) can return the value of the FooBar field.

As mentioned above, CORS requests generally do not carry cookies, so if we want to send cookies to the server, the server must specify access-Control-allow-credentials :true, and the server must specify access-Control-allow-credentials :true. The developers need to turn on the withCredentials attribute for AJAX requests as follows:

	let xhr = new XMLHttpRequest()
	xhr.withCredentials = true
Copy the code

The access-Control-allow-Origin attribute cannot be set to *, and must be specified with the same domain name as the web page. At the same time, cookies still follow the same Origin policy. Only the Cookie set with the server domain name will be uploaded, other domain name Settings will not be uploaded, and the document. Cookie across the source of the original web page code can not read the Cookie under the server domain name