1. Ajax request limits

Ajax can only send requests to its own server.

For example, if there is A website A and A website B, the HTML files in website A can only send Ajax requests to the server of website A, and the HTML files in website B can only send Ajax requests to the server of website B, but website A cannot send Ajax requests to website B. Similarly, website B cannot send Ajax requests to website A

When Web site A sends an Ajax request before Web site B, we call it A cross-domain request

For example, opening an AJAX file locally requires the server to request content

The error is not familiar. This is because a cross – domain request caused the error

2. What is homology

For security reasons, browsers enforce the same-origin policy, which means cross-domain requests are not allowed by default

Here the same origin refers to: the protocol name, host number, port number these three parts are the same. Requests between the same domains are unrestricted, and different domains cannot request each other, which is the same origin policy of Ajax

If two pages have the same protocol, domain name, and port, then both pages belong to the same source, and if one of them is different, they are different sources

The homology policy is to protect the security of user information and prevent malicious websites from stealing data. The original homology policy means that website A sets cookies on the client side and website B cannot access them

3. Resolve cross-domain requests

By default, Ajax does not allow cross-domain requests, but we often have non-same-origin requests, and the task is to resolve cross-domain requests

There are four ways to resolve cross-domain requests:

  1. JSONPResolve cross-domain requests
  2. CORSCross-domain resource sharing
  3. Proxy server
  4. Based on the<iframe>The label

Understand the first two

3.1 JSONPResolve cross-domain requests

JSONP is not part of an Ajax request, but it can simulate an Ajax request

Have you ever wondered that the SRC attribute of , ,

Of course, of course,

In three steps:

  1. Write the server request addresses for different sources in<script>Of the labelsrcProperties of the
< script SRC = "" > < / script >
  1. The server-side response data must be a function call, and the actual data to be sent to the client needs to be the parameters of the function call
Const data = "getData({namer: ", song: "big fish "})"; res.rend(data); // Send data
  1. Define the function at global scope (both functions have the same name)
Function getData(options) {alert(options.namer + '+ options.song')}



The < body > < script > function getData (data) {alert (data) namer + 'sang a' + data. The song)} < / script > < script SRC = "" > < / script > < / body >

Server side:

App. get('/test', function(req, res) {let data = 'getData({namer: "", song:" ")' res.send(data)})

The json optimization

The first is to pass the function name to the server via the URL

We can pass a local function as a parameter through a URL, right? Callback =getData to let the server know the name of the local function

The advantage of this is that the client changes the function name and the server is not affected

    function getData(data) {
        alert(data.namer + '唱了一首' + data.song)
<script src="></script>
App. Get ('/test ', function (the req, res) {res. The json ({namer: 'memory', song: 'actors'})})

The JSONP function already does this for us. It automatically gets the value of the callback as a function, so the server just needs to pass the data

The second way is to turn a script request into a dynamic request

</button> </button> <script> function getData(data) {alert(data.namer + '+ data.song')} </script> <script type="text/javascript"> let btn = document.querySelector('button'); btn.onclick = function() { let script = document.createElement('script'); Script. The SRC = ''; document.body.appendChild(script); / / for the script to add the onload event, kick down the ladder script. The onload = function () {document. Body. RemoveChild (script)}; }; </script>

The script tag is dynamically created when the request is sent, and deleted immediately after the request is finished

But do we have to write this mess every time? I knew I was going crazy when I said that

Let’s wrap a JSONP function

Function jsonp(options) {// let script = document.createElement('script') // let params = "; For (let key in options.data) {params += '&' + key + '=' + options.data[key]} Let fnName = 'myFn' + Math.random().toString().replace('.', '); // window[fnName] = options.success; // fnName = options.success; script.src = options.url + '? callback=' + fnName + params; Document. The body. The appendChild (script) / / script for scripts to add the onload event. The onload = function () {/ / delete the script tag document.body.removeChild(script) } }

Call JSONP (you need to import the JSONP function yourself)

<body> <button id=" XZQ "</button> <button id="zs" </button> <script type="text/javascript"> let btn1 =" document.querySelector('#xzq'); let btn2 = document.querySelector('#zs'); Btn1. Onclick = function () {json ({url: '' data: {namer: 'memory', song: 'just right'}, success: function(data) { alert(data.namer + '--' + data.song); }})}; Btn2. Onclick = function () {json ({url: '' data: {namer: 'week deep, song:' fish '}, success: function(data) { alert(data.namer + '--' + data.song); }})}; </script> </body>


app.get('/test', function(req, res) {

3.2 CORSCross-domain resource sharing

CORS is called Cross-Origin ResCourse Sharing, namely cross-domain resource Sharing, which is a new mechanism launched by W3C.

It allows the browser to send Ajax requests to cross-domain servers, overcoming the limitation that Ajax can only be used with the same origin

So, when we use CORS to handle a cross-domain request, the browser determines that this is a cross-domain request, and will automatically help us handle the appropriate cross-domain request configuration, add some additional header information, and we just have to decide on the server side whether to allow this domain access

1. Simple requests

A simple request must satisfy three requests:

  1. The request mode isGET,POST,HEAD
  2. The data typeContent-TypeCan only beapplication/x-www-form-urlencoded,multipart/form-datatext/plain
  3. Custom request headers are not used

So, if it’s a simple request, you can set a header that allows cross-domain requests

On the server side:

app.post('/cache', function(req, res) { res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8080') res.send(' You must go until the lights are on ')})

The http://localhost:8080 field is allowed to request, and if we want any field to be able to request, we simply replace it with *

res.setHeader('Access-Control-Allow-Origin', '*')

Now any AJAX from the domain that requests the server will be granted access and can respond to the data normally

2. Pre-request

A domain request is a relatively complex request and is considered a pre-request when the following conditions occur

  1. The request is made byGET,POST,HEADOther ways, such as:PUT,DELETE
  2. usePOSTRequest, but the data type isapplication/xmlortext/xmlOf the XML data type
  3. Use custom request headers

3. Requests with credential information

The XMLHttpRequest object sends credentials (cookies and authentication information) along with the request, but cross-domain requests are not

So if you want to pass the Cookie to the server, you need to set the permission to send the credential information in the request header. Both the client and the server need to be set up

If you’re interested, you can keep exploring……


  1. AjaxThe same origin policy means that only domains with the same protocol, host number, and port can make requests. The purpose of this policy is to secure and prevent site information from being stolen
  2. There are many ways to resolve cross-domain requests,JSONPThe requested scripts are executable scripts suitable for requesting our own servers
  3. CORSH5 is a new feature that supports almost all requests and is commonly used. The drawback is that lower versions of browsers can have compatibility issues