当前位置:网站首页>Stop saying that you can't solve the "cross domain" problem
Stop saying that you can't solve the "cross domain" problem
2022-07-01 03:04:00 【Lingxiyun】
List of articles
What is? “ Across the source ”
In fact, what we usually call cross domain is a narrow request scenario , In a nutshell “ Span “ too browser Of The same-origin policy Go and ask for information “ Source ”, So we call it “ Across the source ” No problem . that “ Across the source ”, What is the source ? What is the homology strategy of browsers ?
const url = 'https://www.google.com:3000'
Like this one above URL, Agreement is :https, Domain name is www.google.com, The port is 3000. What happens to different sources ? There will be many restrictions , such as :
- Cookie,LocalStorage,IndexDB Wait for the storage content to be unreadable
- DOM Node cannot access
- Ajax The request was sent , But the response was intercepted by the browser
Why do you want to make such a thing to limit ? Based on safety considerations , Without it , May come across :
- Cookie hijacked , Stolen data by malicious websites
- More vulnerable XSS,CSRF attack
- Unable to isolate potentially malicious files
- … …
So there must be . Precisely because Browser homology strategy The existence of ,Ajax The request may have been intercepted after it was sent , It will also give you an error :
* Access to XMLHttpRequest at 'xxx' from origin 'xxx' has been block by CORS,
policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
This feeling that you can't get a response , Very afflictive

Next, let's take a look at how to use scientific methods to solve cross domain problems .
JSONP
Namely The front-end uses <script> Labeled src Property has no cross domain limitation , Can be dynamically generated from other sources JSON data . Why call JSONP ?JSONP yes JSON with Padding Abbreviation , The specific implementation idea is roughly divided into the following steps :
- The script of this site creates a Elements ,src The address points to the server that requests data across domains
- Provide a callback function to receive data , The function name can be agreed through address parameter passing
- After the server receives the request , Return a wrapper JSON Response string for data , Like this :callback({…})
After the browser receives the response, it will execute the callback function callback, Pass parsed JSON Object as parameter , So that we can callback Processing data in . In development , You will encounter the same callback function name , You can simply encapsulate a JSONP function :
function jsonp({
url, params, callback }) {
return new Promise((resolve, reject) => {
// Create a temporary script The tag is used to initiate a request
const script = document.createElement('script');
// Temporarily bind the callback function to window object , After the callback function is executed , remove script label
window[callback] = data => {
resolve(data);
document.body.removeChild(script);
};
// structure GET Request parameters ,key=value&callback=callback
const formatParams = {
...params, callback };
const requestParams = Object.keys(formatParams)
.reduce((acc, cur) => {
return acc.concat([`${
cur}=${
formatParams[cur]}`]);
}, [])
.join('&');
// structure GET Requested url Address
const src = `${
url}?${
requestParams}`;
script.setAttribute('src', src);
document.body.appendChild(script);
});
}
// Invocation time
jsonp({
url: 'https://xxx.xxx',
params: {
...},
callback: 'func',
})
Promise Encapsulates the request , Make asynchronous callbacks more elegant , It's essentially :
<script src='https://xxx.xxx.xx?key=value&callback=xxx'><script>
JSONP Of The advantage is simplicity and good compatibility , however The disadvantages are obvious , Server support is required and only GET request , Let's look at the second scheme , It is also the mainstream cross domain solution , Focus on !
CORS
CORS(Cross-Origin Resource Sharing) The full name of Cross-domain resource sharing , It's actually a mechanism . The browser has a homology strategy , It's not very friendly for developers , Because it may often be necessary to initiate a cross domain HTTP request . I said before , Cross domain requests are actually sent , Just blocked by the browser , Because it's not safe , To put it bluntly , You want to get something from the server , But without the permission of others . So what's safe ? If the server allows it, it is not safe , This is it. CORS Realized principle : Use extra HTTP Head to the browser , Let run on a certain initial Web The application allows access to specified resources from servers of different origin .
- Compatibility
at present , All major browsers support CORS, among ,IE The browser version cannot be lower than 10,IE 8 and 9 Need to pass through XDomainRequest To achieve
- Realization principle
CORS Requires both browser and server support , Whole CORS Communication process of , It's all done automatically by the browser .
- How automatic ?
browserOnce it is found that the request is a cross domain request , First, we will judge the type of request , If it isA simple request, Will be inAdd a... In the request header Origin Field, Indicates which source the request is from .
The serverAfter receiving the request , Will return a response ,Response headIt will include a name calledAccess-Control-Allow-OriginField of , Its value is either contained by Origin The domain name specified in the header field , Or a "*",To accept a request for any domain name. If there is no such field in the response header , It means that the current source is not within the license scope of the server , The browser will report an error .
GET /cors HTTP/1.1
Origin: https://xxx.xx
Accept-Language: en-US
Connection: keep-alive
... ...
If it is It's not a simple request , Will be before formal correspondence , Send a Pre inspection request (preflight), The purpose is to ask the server , Whether the domain name of the current web page is in the server's license list , And what can be used HTTP Verb and header fields , Only a positive response , The browser will make a formal request , Otherwise, it will be wrong . In daily development , You will see a lot of use OPTION Method , It's actually a pre inspection request :
OPTIONS /cors HTTP/1.1
Origin: http://xxx.xx
Access-Control-Request-Method: PUT
Accept-Language: en-US
... ...
- What are simple requests , Which are non simple requests ?
Not trigger CORS Pre checked , It's a simple request. Which requests do not trigger a pre check ? Use one of the following methods :GET, HEAD, POST, alsoContent-TypeIs limited to one of the following three values :
- text/plain
- multipart/form-data
- application/x-www-form-urlencoded
contrary ,
What does not meet the above conditions is a non simple request. thereforeRealization CORS The key is the server , As long as the server implements it CORS Related interfaces of , Cross domain.CORS And JSONP comparison ,advantageIs to support all request methods ,shortcomingIt is more compatible JSONP Bad .
except JSONP and CORS Outside , There is also a common cross domain solution :PostMessage, It is more used for message passing between windows .
PostMessage
PostMessage yes Html5 XMLHttpRequest Level 2 Medium API, It can realize cross document communication (Cross-document messaging). Compatibility ,IE8+,Chrome,Firfox And other mainstream browsers support ,
- How to understand cross document communication ?
Sure
Release in analogy design pattern - A subscription model, ad locum , A window sends messages , Another window accepts messages , The reason why it is said that it is similar to the release - A subscription model , Not observer mode , It's because hereThere is no direct communication between the two windows , But through the browser, a third-party platform.
window.postMessage(message, origin, [transfer])
postMessage Method to receive three parameters , want Message sent 、 The source of the message And a Optional Transferable object , How to receive messages ?
window.addEventListener("message", function receiveMessage(event) {
}, false); // recommend , Better compatibility
window.onmessage = function receiveMessage(event) {
} // Not recommended , This is an experimental function , Compatibility is not as good as the above method
After receiving the message , Message object event Contains three properties :source、origin、data, among data It's sent message. Besides , In addition to window communication ,postMessage It can also be the same as Web Worker and Service Work communicate .
Websocket
Websocket yes HTML5 A persistent protocol , The full duplex communication between browser and server is realized , It is also a cross-domain solution .
- What is full duplex communication ?
Namely
After establishing the connection ,server And client Can actively send or receive data to each other. Native WebSocket API It's not very convenient to use , Usually choose to encapsulate one by yourself Websocket Or use an existing third-party library .
Here is a third-party library ws For example :
const WebSocket = require('ws');
const ws = new WebSocket('ws://www.host.com/path');
ws.on('open', function open() {
ws.send('something');
});
ws.on('message', function incoming(data) {
console.log(data);
});
... ...
notes :Websocket It's a long connection , Create multiple in one page Websocket Connectivity can cause performance problems .
Nginx Reverse proxy
The same origin policy limits : The standards that the browser needs to follow when sending cross domain requests to the server .
- What if the server sends a cross domain request to the server ?
Certainly
Not restricted by the same origin policy of the browser. Use this idea , CanBuild a proxy server , Accept client requests , Then forward the request to the server , After the proxy server gets the response , Then forward the response to the client.

Nginx Reverse proxy only needs simple configuration to realize cross domain :
# nginx.config
# ...
server {
listen 80;
server_name www.domain1.com;
location / {
proxy_pass http://www.domain2.com:8080; # Reverse proxy
proxy_cookie_domain www.domain2.com www.domain1.com; # modify cookie In the domain name
index index.html index.htm;
# When used webpack-dev-server Such as middleware proxy interface access nignx when , No browser is involved at this time , So there is no homologous restriction , The following cross-domain configuration is not enabled
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Credentials true;
# ...
}
}
Node Middleware agent
The principle of the implementation is the same as that of the proxy server mentioned above , It's just used here Node Middleware as a proxy .
notes :
The browser still follows the same origin policy when requesting from the proxy server, Don't forget it. Node Layers pass through CORS Do cross domain processing .
const https = require('https')
// Accept client requests
const sever = https.createServer((req, res) => {
...
const {
method, headers } = req
// Set up CORS Allow cross-domain
res.writeHead(200, {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': '*',
'Access-Control-Allow-Headers': 'Content-Type',
...
})
// Request server
const proxy = https.request({
host: 'xxx', method, headers, ...}, response => {
let body = ''
response.on('data', chunk => {
body = body + chunk })
response.on('end', () => {
// The response result is forwarded to the client
res.end(body)
})
})
// End request
proxy.end()
})
document.domain
When the secondary domain name is the same , Set up document.domain Cross domain .
- What is a secondary domain name ?
a.test.com and b.test.com It belongs to the secondary domain name , They are all test.com The subdomain of .
How to implement cross-domain ?
document.domain = 'test.com' // Set up domain identical
// adopt iframe Embed cross domain pages
const iframe = document.createElement('iframe')
iframe.setAttribute('src', 'b.test.com/xxx.html')
iframe.onload = function() {
// Get iframe After instance, you can directly access iframe Data in
console.log(iframe.contentWindow.xxx)
}
document.appendChild(iframe)
summary
Of course , In addition to the above scheme , Compare Hack( invasion ) And :window.name、 location.hash, But these cross domain approaches are now Not recommended , Why? ? Because by contrast, there are More secure and powerful PostMessage As a substitute . There are actually many cross domain solutions , Sum up :
- CORS Support all HTTP request , yes
The most mainstream cross domain solution- JSONP Only support GET request , But it can.
Compatible with old browsers- Node Middleware and Nginx Reverse proxy takes advantage of
Server to serverNo homology policy restrictions- Websocket It is also a cross domain solution
- PostMessage Cross document communication can be realized , More
For window communication- document.domain、window.name、location.hash Gradually fade out the stage of history , As a substitute PostMessage It's a good plan
边栏推荐
- Communication protocol -- Classification and characteristics Introduction
- Introduction and basic knowledge of machine learning
- Redis分布式锁的8大坑
- 鼠标悬停效果二
- How to open a stock account? Also, is it safe to open an account online?
- servlet【初识】
- 【小程序项目开发-- 京东商城】uni-app之分类导航区域
- If a parent class defines a parameterless constructor, is it necessary to call super ()?
- A small document of JS method Encyclopedia
- Druid监控统计数据源
猜你喜欢

Optimal transport Series 1

第03章_用户与权限管理

Restcloud ETL data realizes incremental data synchronization through timestamp

php批量excel转word
![[QT] add knowledge supplement of third-party database](/img/ea/ca8b07ad80485208f2bb8ee8a78a28.png)
[QT] add knowledge supplement of third-party database

如何校验两个文件内容是否相同

So easy deploy program to server

Prototype and prototype chain in JS

通信协议——分类及其特征介绍

STM32 - DS18B20 temperature sampling of first-line protocol
随机推荐
【小程序项目开发-- 京东商城】uni-app之首页商品楼层
[small program project development -- Jingdong Mall] the home page commodity floor of uni app
ssh配置免密登录时报错:/usr/bin/ssh-copy-id: ERROR: No identities found 解决方法
Mouse over effect V
Why are strings immutable in many programming languages? [repeated] - why are strings immutable in many programming languages? [duplicate]
Optimal transport Series 1
Error accessing URL 404
[applet project development -- Jingdong Mall] user defined search component of uni app (Part 1)
A shooting training method based on the digital measurement of Joule energy and posture of sphygmomanometer air bag with standard air pressure
js中的原型和原型链
Communication protocol -- Classification and characteristics Introduction
Huawei operator level router configuration example | configuration static VPLS example
Network address translation (NAT) technology
Poj-3486-computers[dynamic planning]
Codeforces Round #416 (Div. 2) C. Vladik and Memorable Trip
Mouse over effect 7
【EXSI】主机间传输文件
性能测试常见面试题
Detailed explanation of pointer array and array pointer (comprehensive knowledge points)
Big orange crazy blog move notice