Ajax cross-domain request

Ajax cross-domain request

1. Ajax request limit

Ajax
You can only send requests to your own server .

For example, there is a website A and a website B. The HTML files in the A website can only send Ajax requests to the A website server, and the HTML files in the B website can only send Ajax requests to the B website server, but the A website cannot send B If the website sends Ajax requests, similarly, website B cannot send Ajax requests to website A

when

A
Site B is sent first
Ajax
Request, we call it a cross-domain request

Such as: open locally

AJax
File first server request content

The above error is not familiar, this is because an error caused by a cross-domain request has occurred

2. What is homology

For security reasons, the browser has made the same-origin policy restriction, that is, cross-domain requests are not allowed by default

The homology mentioned here means that the three parts of the protocol name, host number, and port number are the same. Requests between the same domain are not restricted, and different domains cannot request each other. This is

Ajax
Same Origin Strategy

If two pages have the same protocol, domain name, and port, then the two pages belong to the same source, and as long as one of them is different, it is a different source

The same-origin policy is to protect the security of user information and prevent malicious websites from stealing data. The original same-origin policy refers to the setting of A website on the client side.

Cookies
, Website B cannot be accessed

3. Resolve cross-domain requests

Ajax
Cross-domain requests are not allowed by default, but we often make non-same-origin requests. What we have before us is to resolve cross-domain requests

There are 4 ways to resolve cross-domain requests:

  1. JSONP
    Resolve cross-domain requests
  2. CORS
    Cross-domain resource sharing
  3. Proxy server
  4. based on
    <iframe>
    label

Mainly understand the first two

3.1
JSONP
Resolve cross-domain requests

JSONP
Does not belong
Ajax
Request, but it can simulate
Ajax
request

Have you ever thought that we usually

<img>
,
<link>
,
<script>
Etc. in the label
src
Attributes are not subject to cross-domain requests, so can we also make
<script>
Go to request the server's JS file to get the data?

of course
of course

It is divided into three steps:

  1. Write the server request addresses of different sources in
    <script>
    Labelled
    src
    Properties
<script src= "http://127.0.0.1:3000/test" ></script> Copy the code
  1. The server response data must be a function call, and the data to be sent to the client must be used as a function call parameter
const Data = 'the getData ({Namer: " Week deep ", song: " Big Fish "}) " ; res.rend(data); //Send data copy code
  1. Define the function in the global scope (the two function names must be the same)
function getData ( options ) { alrt(options.namer + 'sing a song' + options.song) } Copy code

chestnut:

Client:

< body > < script > function getData ( data ) { alrt(data.namer + 'sing a song' + data.song) } </Script > < Script the src = "http://127.0.0.1:3000/test" > </Script > </body > copy the code

Service-Terminal:

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

JSONP optimization

The first type: pass the function name to the server via URL

We can pass the local function

URL
Pass on
?callback=getData
Way to let the server know the name of the local function

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

<script> function getData ( data ) { alrt(data.namer + 'sing a song' + data.song) } </script> < Script the src = "http://127.0.0.1:3000/test?callback=getData> </Script> copy the code
app.get( '/test' , function ( req, res ) { res.jsonp({ namer : ' ' , song : 'Actor' }) }) Copy code

jsonp
The function has done the processing for us and will automatically get the parameters
callback
The value of as a function, so the server only needs to pass data

The second type: change the script request into a dynamic request

<button>button</button> < script > function getData ( data ) { alrt(data.namer + 'sing a song' + data.song) } </script > < script type = "text/javascript" > let btn = document .querySelector( 'button' ); btn.onclick = function () { let script = document .createElement( 'script' ); script.src = 'http ://127.0.0.1:3000/test ' ; document .body.appendChild(script); //Add onload event to script, cross the river and demolish the bridge script.onload = function () { document .body.removeChild(script) }; }; </script > copy code

Dynamically created when sending the request

script
The label was sent, and it was deleted immediately after the end

But do we have to write such a bunch of code every time? When I said this, I knew I was going crazy again

Let's encapsulate one

jsonp
Function bar

function jsonp ( options ) { //Create tag let script = document .createElement( 'script' ) //splicing string let params = '' ; for ( let key in options.data) { params += '&' + key + '=' + options.data[key] } //Create a random function, toString removes the decimal point from the number conversion string. let fnName = 'myFn' + Math .random().toString().replace( '.' , '' ); //fnName is not a global function, use window turns it into a function window [fnName] = options.success; script.src = options.url + '?callback=' + fnName + params; document .body.appendChild(script) //Add an onload event to the script tag script.onload = function () { //Delete the script tag document .body.removeChild(script) } } Copy code

transfer

jsonp
(Need to import by yourself
jsonp
function)

< body > < button id = "xzq" > Xue Zhiqian </button > < button id = "zs" > Zhou Shen </button > < script type = "text/javascript" > let btn1 = document .querySelector( '#xzq ' ); let btn2 = document .querySelector( '#zs' ); btn1.onclick = function () { jsonp({ url: 'http://127.0.0.1:3000/test', data: { namer: ' ', song: ' ' }, success: function(data) { alrt(data.namer + '--' + data.song); } }) }; btn2.onclick = function() { jsonp({ url : 'http : //127.0.0.1 : 3000/test ' , data : { namer : 'Zhou Shen' , song : ' ' }, success : function ( data ) { alrt(data.namer + '--' + data.song); } }) }; </script > </body > Copy code

Backstage:

app.get( '/test' , function ( req, res ) { res.jsonp(req.query) }) Copy code

3.2
CORS
Cross-domain resource sharing

CORS
Full name
Cross-origin Rescourse Sharing
, Namely cross-domain resource sharing, is a new mechanism launched by W3C.

It allows the browser to send to the cross-domain server

Ajax
Request, overcome
Ajax
Restriction that only the same source can be used

So when we are using

CORS
When processing a cross-domain request, the browser judges that this is a cross-domain request, and will automatically help us handle the corresponding cross-domain request configuration, adding some additional header information, and all we have to do is to determine whether this is allowed on the server side Domain access

1. Simple request

A simple request must satisfy three requests:

  1. GET
    POST
    HEAD
  2. Content-Type
    application/x-www-form-urlencoded
    multipart/form-data
    text/plain

app.post('/cache', function(req, res) { res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8080') res.send(' ') })

http://localhost:8080
*

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

Ajax

2

  1. GET
    POST
    HEAD
    PUT
    DELETE
  2. POST
    application/xml
    text/xml
    XML

3

XMLHttpRequest
Cookie

Cookie

......

  1. Ajax
  2. JSONP
  3. CORS
    H5