Cross-domain basic knowledge points: Cross-domain knowledge points
Four ways for iframe to achieve cross-domain: Four ways for iframe to achieve cross-domain
Note: The virtual host used in this article is also configured in the iframe above.
Table of Contents
JSONP cross domain
Introduction to JSONP
Cross-domain experiments:
WebSocket cross domain
Introduction to websockets
Cross-domain experiments
JSONP cross-domain
JSONP Introduction
If cross-domain is not involved, the front-end usually obtains data from the server in JSON format. However, this solution is not feasible when cross-domain. However, the JSON book can be shared across domains after simple processing. This is JSONP (JSON with Padding). )plan
You can do some padding before and after the JSON string (this is where the name JSONP comes from), and you can turn it into a piece of javascript code.
JSONP is a common method for cross-origin communication between servers and clients.
The biggest feature is that it is simple and easy to use, there are no compatibility issues, all old browsers support it, and the server-side modification is very small.
Here’s how it does it:
Method 1: When passing parameter JSON data through a function, you need to define the callback function (Callback) in advance, and then load the JSON code through ““. Zhang callback function gets the JSON data
Method 2: Another way is to assign the data to a variable through an assignment statement, which can also introduce JSON data into the current Javascript execution environment.
shortcoming:
-
Transferring little data
-
Only supports get transmission (similar to the status of RIP protocol)
The first step is to add a element to the web page and request a script from the server. This is not restricted by the same-origin policy and can be requested across domains.
<script src="http://api.foo.com?callback=bar"></script>
Note that the requested script URL has a callback
parameter (?callback=bar
), which is used to tell the server the name of the client's callback function (bar
).
In the second step, after the server receives the request, it concatenates a string, puts the JSON data in the function name, and returns it as a string (bar({...})
).
In the third step, the client will parse the string returned by the server as a code, because the browser believes that this is the script content requested by the tag.
At this time, as long as the client defines the bar()
function, it can get the JSON data returned by the server in the function body.
Let's look at an example below. First, the element is dynamically inserted into the web page, which makes a request to the cross-domain URL.
function addScriptTag(src) { var script = document.createElement('script'); script.setAttribute('type', 'text/javascript'); script.src = src; document.body.appendChild(script); } ? window.onload = function () { addScriptTag('http://example.com/ip?callback=foo'); } ? function foo(data) { console.log('Your public IP address is: ' + data.ip); };
The above code makes a request to the server example.com
by dynamically adding the element.
Note that the query string of this request has a callback
parameter that specifies the name of the callback function, which is required for JSONP.
After the server receives this request, it will put the data in the parameter position of the callback function and return it.
foo({ 'ip': '8.8.8.8' });
Since the script requested by the element is run directly as code, at this time, as long as the browser defines the
foo
function, the function will be called immediately.
JSON data as parameters are treated as JavaScript objects rather than strings, thus avoiding the step of using JSON.parse
.
Cross-domain experiment:
(1) Write cross_origin/index.html
function foo(data) { console.info(data); } var obj = { 'ip': '8.8.8.8' } foo(obj)
The index.html here acts as the server. This class provides a foo function, which passes the value in the obj object into the foo function and types it out.
(2) Write CSSinject/index.html file
function addScriptTag(src) { var script = document.createElement('script'); script.setAttribute('type', 'text/javascript'); script.src = src; document.body.appendChild(script); } ? window.onload = function () { addScriptTag('http://www.aaa.com/index.html?callback=foo'); } ? function foo(data) { console.log('Your public IP address is: ' + data.ip); };
Here we first define a function to use script tags, then open a loading time, pass www.aaa.com/index.html?callback=foo into the above function, and then callback=foo in the parameter The callback function is specified as foo, and the callback function is executed after accessing www.aaa.com.
(3) Test
Enter www.security.com in the browser to access the CSSinject/index.html page
As you can see, the IP address defined in www.aaa.com was successfully printed.
Summary: The JSONP solution is not actually a standard practice for cross-domain data transmission, it is just a technique, and it can only achieve one-way read operations (only supports GET requests), and write operations require the help of other solutions to achieve cross-domain The standard transmission solution is the CORS cross-domain resource sharing solution that will be discussed later. JSONP's cross-domain implementationThis method has long been eliminated
WebSocket cross-domain
websocket introduction
WebSocket is a communication protocol that uses ws://
(non-encrypted) and wss://
(encrypted) as protocol prefixes.
This protocol does not implement a same-origin policy, and cross-origin communication can be carried out through it as long as the server supports it.
The following is an example of the header information of a WebSocket request issued by the browser
GET /chat HTTP/1.1 Host: server.example.com Upgrade: websocket Connection: Upgrade Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw== Sec-WebSocket-Protocol: chat, superchat Sec-WebSocket-Version: 13 Origin: http://example.com
In the above code, there is a field called Origin
, which indicates the request source (origin) of the request, that is, the domain name from which it was sent.
It is precisely because of the Origin
field that WebSocket does not implement the same origin policy.
Because the server can determine whether to allow this communication based on this field, if the domain name is in the whitelist, the server will respond as follows:
HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk= Sec-WebSocket-Protocol: chat
Cross-domain experiment
(1) Create the file socket.html (under the CSSinject directory)
let socket = new WebSocket('ws://127.0.0.1:3000'); socket.onopen = function () { socket.send('i love you ');//Send data to the server } socket.onmessage = function (e) { console.log(e.data);//Receive data returned by the server }
Here is a common instance object socket of the Websket constructor, and ws is 127.0.0.1:3000, then a new open event is created, the sentence 'i love you' is sent to the server, and a new message event is created later. , print the message returned by the server
(2) Create the file socket.js (under the CSSinject directory)
let express = require('express'); let app = express(); let WebSocket = require('ws')//Remember to install ws let wss = new WebSocket.Server({ port: 3000 }); wss.on('connection', function (ws) { ws.on('message', function (data) { console.log(data); ws.send('i hate you') }); })
First, I imported the express module, then introduced the ws module of Websocket, created a new websocket instance, listened to port 3000, and then executed the ws callback function when the client connected successfully (the message sent by the client was received here), and then replied One sentence'i hate you'
Note: If there is no ws module, you can use the npm install ws command to install it.
If you don’t have the npm command, you can browse and search for node.js and install it locally.
(3) Test
First use the cmd command line to enter the corresponding directory and simulate running the js file on the server.
node socket.js
Then visit www.security.com/socket.html in the browser
You can see that the client successfully received the information sent by the server
Look at the server again:
This is a string of hexadecimal numbers. We can try to convert this string of numbers into ASCII code:
First, the result of converting to decimal is: 105 32 108 111 118 101 32 121 111 117 32
Then corresponding to the ASCII code table, this string of characters can be decoded as: i love you
That means we have successfully implemented cross-domain resource access between the client and the server!
There is another article about the cross-domain method, CORS cross-domain, which is also the most recommended method. It will be explained in this article.
The knowledge points of the article match the official knowledge files, and you can further learn related knowledge. Network Skill TreeHomepage Overview 42421 people are learning the system