First, mention the browser’s same-origin policy, which is a deliberate feature limitation:

The same origin policy defines that pages from different sources cannot access each other’s data. This is deliberately designed by browsers to protect users’ privacy.

Source = Protocol + domain name + port number

If the protocol, domain name, and port number of two urls are the same, the two urls are of the same origin.

For example: qq.com and www.qq.com are not of the same origin

Cross-domain: Data is transferred between different domains. If the protocol, domain name, or port is different, the data is cross-domain.

But why cross-domain CSS, JS, images, etc?

A: The same-origin policy restricts data access. When we refer to CSS, JS, and images, we don’t know what they are, we just refer to them.

JSONP, CORS are used to implement cross-domain.

The json cross domain:

Support only GET requests, do not support other requests such as POST, do not support complex requests, only support simple requests.

CORS cross domain:

Supports all requests, including GET, POST, OPTOIN, PUT, and DELETE. Both complex and simple requests are supported.

Purpose of USING JSONP and CORS: The purpose of using JSONP and CORS is the same, and both servers and clients need to support, but CORS is more powerful.

CORS (Cross-domain Resource Sharing)

If you want to share data, you need to declare it in advance, the browser says. Write localhost:9999 in the localhost:8888 header to access it.

Grammar:

Access-Control-Allow-Origin:http://foo.example
response.setHeader('Access-Control-Allow-Origin', 'http://localhost:9999')
Copy the code

JSONP:

When we cross domains, since the browser does not support CORS, we have to use another way to cross domains, so we request a JS file that will perform a callback, which will contain our data. The name of the callback is a random number that can be generated at random. We pass the callback argument to the background, which will return the number to us and execute it.

Advantages: Compatible with IE and cross-domain

Cons: Because it’s a Script tag, it can’t read the exact state of Ajax, only success or failure. It can only send GET requests and does not support POST.