1. Ajax request limit
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
Such as: open locally
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
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.
3. Resolve cross-domain requests
There are 4 ways to resolve cross-domain requests:
- JSONPResolve cross-domain requests
- CORSCross-domain resource sharing
- Proxy server
- based on <iframe>label
Mainly understand the first two
3.1 JSONP Resolve cross-domain requests
Have you ever thought that we usually
It is divided into three steps:
- Write the server request addresses of different sources in<script>LabelledsrcProperties
<script src= "http://127.0.0.1:3000/test" ></script>
Copy the code
- 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
- 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
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
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
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
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
< 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
It allows the browser to send to the cross-domain server
So when we are using
1. Simple request
A simple request must satisfy three requests:
- GETPOSTHEAD
- Content-Typeapplication/x-www-form-urlencodedmultipart/form-datatext/plain
app.post('/cache', function(req, res) {
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8080')
res.send(' ')
})
res.setHeader('Access-Control-Allow-Origin', '*')
2
- GETPOSTHEADPUTDELETE
- POSTapplication/xmltext/xmlXML
3
......
- Ajax
- JSONP
- CORSH5