当前位置:网站首页>Work report of epidemic data analysis platform [4] cross domain correlation
Work report of epidemic data analysis platform [4] cross domain correlation
2022-06-12 04:14:00 【m0_ fifty-five million six hundred and seventy-five thousand ei】
When deploying the backend , Cross domain setting is basically a problem that must be solved .
CORS It's a W3C standard , The full name is " Cross-domain resource sharing "(Cross-origin resource sharing). It allows the browser to cross to the source server , issue XMLHttpRequest request , To overcome AJAX A restriction that can only be used with the same origin .
CORS Requires both browser and server support . at present , All browsers support this feature ,IE The browser cannot be lower than IE10.
Whole CORS Communication process , It's all done automatically by the browser , No user involvement is required . For developers ,CORS Correspondence and homology AJAX There is no difference in communication , The code is exactly the same . Once the browser finds AJAX Request cross source , Will automatically add some additional header information , Sometimes there is an additional request , But users don't feel .
therefore , Realization CORS The key to communication is the server . As long as the server implements it CORS Interface , You can communicate across sources .
Two requests
The browser will CORS Requests fall into two categories : A simple request (simple request) And not a simple request (not-so-simple request).
As long as the following two conditions are met , It's a simple request .
(1) The request method is one of three :
HEAD
GET
POST
(2)HTTP The header information of does not exceed the following fields :
Accept
Accept-Language
Content-Language
Last-Event-ID
Content-Type: Three values only application/x-www-form-urlencoded、multipart/form-data、text/plain
What is cross-domain ?
In the front-end world , Cross domain means that the browser allows cross domain requests to be sent to the server , To overcome Ajax A restriction that can only be used with the same origin .
When a cross domain failure occurs, you will receive an error Access-control-Allow-origin. When the web page can't be printed , You can see whether there is this error from the developer tool .
The same-origin policy
The same origin policy is a convention , from Netscape company 1995 Browser introduced in , It is the core and most basic security feature of the browser , If the same origin policy is missing , Browsers are easily accessible XSS、CSFR Such attacks . So homologous means " agreement + domain name + port " All the same , Even if two different domains point to the same one ip Address , Nor a homologous .
The homology strategy limits the following behaviors :
Cookie、LocalStorage and IndexDB Can't read
DOM and JS Object can't get
AJAX Request cannot be sent
Enable cross domain
1.JSONP Cross domain
principle : Is the use
shortcoming : Can only send get A request .
Realization :
1) Native JS Realization :
<script>
var script = document.createElement('script');
script.type = 'text/javascript';
// Pass a callback function name to the back end , It is convenient to execute the callback function defined in the front end when the back end returns
script.src = 'http://www.domain2.com:8080/login?user=admin&callback=handleCallback';
document.head.appendChild(script);
// Callback execution function
function handleCallback(res) {
alert(JSON.stringify(res));
}
</script>
The server returns as follows ( On return, the global function is executed ):
handleCallback({
"success": true, "user": "admin"})
jquery Ajax Realization :
$.ajax({
url: 'http://www.domain2.com:8080/login',
type: 'get',
dataType: 'jsonp', // The request method is jsonp
jsonpCallback: "handleCallback", // Custom callback function name
data: {
}
});
Vue axios Realization :
this.$http = axios;
this.$http.jsonp('http://www.domain2.com:8080/login', {
params: {
},
jsonp: 'handleCallback'
}).then((res) => {
console.log(res);
})
Back end node.js Code
var querystring = require('querystring');
var http = require('http');
var server = http.createServer();
server.on('request', function(req, res) {
var params = querystring.parse(req.url.split('?')[1]);
var fn = params.callback;
// jsonp Back to settings
res.writeHead(200, {
'Content-Type': 'text/javascript' });
res.write(fn + '(' + JSON.stringify(params) + ')');
res.end();
});
server.listen('8080');
console.log('Server is running at port 8080...');
Cross-domain resource sharing (CORS)
CORS It's a W3C standard , The full name is " Cross-domain resource sharing "(Cross-origin resource sharing).
It allows the browser to cross to the source server , issue XMLHttpRequest request , To overcome AJAX A restriction that can only be used with the same origin .
CORS Requires both browser and server support . at present , All browsers support this feature ,IE The browser cannot be lower than IE10.
The browser will CORS Cross domain requests are divided into simple requests and non simple requests .
As long as two conditions are met at the same time , It's a simple request
(1) Use one of the following methods :
head
get
post
(2) Requested Heder yes
Accept
Accept-Language
Content-Language
Content-Type: Three values only :application/x-www-form-urlencoded、multipart/form-data、text/plain
Do not satisfy the above two conditions at the same time , It's not a simple request . The browser handles both , It's different .
A simple request
For simple requests , The browser sends out CORS request . say concretely , It's in the head message , Add one more Origin Field .
GET /cors HTTP/1.1
Origin: http://api.bob.com
Host: api.alice.com
Accept-Language: en-US
Connection: keep-alive
User-Agent: Mozilla/5.0...
In the header above ,Origin Fields are used to describe , Which source is the request from ( agreement + domain name + port ). Server according to this value , Decide whether to agree to the request .
CORS Cross domain examples
Native ajax:
var xhr = new XMLHttpRequest(); // IE8/9 need window.XDomainRequest compatible
// The front end is set with or without tape cookie
xhr.withCredentials = true;
xhr.open('post', 'http://www.domain2.com:8080/login', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send('user=admin');
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
};
jquery ajax:
$.ajax({
...
xhrFields: {
withCredentials: true // The front end is set with or without tape cookie
},
crossDomain: true, // Will make the request header contain additional information across domains , But it doesn't include cookie
...
});
nginx Agent cross domain
nginx Agent cross domain , Substance and CORS The cross domain principle is the same , Set the request response header through the configuration file Access-Control-Allow-Origin… Etc .
nginx Configuration to solve iconfont Cross domain
Browser cross domain access js、css、img And other conventional static resources are licensed by the same origin policy , but iconfont The font file (eot|otf|ttf|woff|svg) exception , At this time can be in nginx The following configuration is added to the static resource server of .
location / {
add_header Access-Control-Allow-Origin *;
}
nginx Reverse proxy interface cross domain
Cross-domain problem : The same origin policy is only a security policy for browsers . Server side call HTTP The interface just uses HTTP agreement , There is no need for homologous strategies , There is no cross domain problem .
Realize the idea : adopt Nginx Configure a proxy server domain name and domain1 identical , Different ports ) For detecting , Reverse proxy access domain2 Interface , And it can be modified incidentally cookie in domain Information , Convenient current field cookie write in , Achieve cross domain access .
nginx Specific configuration :
server {
listen 81;
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 http://www.domain1.com; # The current end is cross-domain only cookie when , for *
add_header Access-Control-Allow-Credentials true;
}
}
nodejs Middleware agent cross domain
node Middleware realizes cross domain agent , The principle is roughly the same as nginx identical , All by starting a proxy server , Realize data forwarding , It can also be set cookieDomainRewrite Parameter modification response header cookie Chinese domain name , Implement the of the current domain cookie write in , Convenient interface login authentication .
Use node + express + http-proxy-middleware Building a proxy The server .
The front-end code :
var xhr = new XMLHttpRequest();
// The front switch : Whether the browser reads or writes cookie
xhr.withCredentials = true;
// visit http-proxy-middleware proxy server
xhr.open('get', 'http://www.domain1.com:3000/login?user=admin', true);
xhr.send();
Middleware server code :
var express = require('express');
var proxy = require('http-proxy-middleware');
var app = express();
app.use('/', proxy({
// Proxy cross domain target interface
target: 'http://www.domain2.com:8080',
changeOrigin: true,
// Modify response header information , Implement cross domain and allow for cookie
onProxyRes: function(proxyRes, req, res) {
res.header('Access-Control-Allow-Origin', 'http://www.domain1.com');
res.header('Access-Control-Allow-Credentials', 'true');
},
// Modify... In the response message cookie domain name
cookieDomainRewrite: 'www.domain1.com' // It can be for false, Means not to modify
}));
app.listen(3000);
console.log('Proxy server is listen at port 3000...');
document.domain + iframe Cross domain
This method can only be used in the case of the same secondary domain name , such as a.test.com and b.test.com Apply to this approach . Just add to the page document.domain ='test.com’ Means that the secondary domain name is the same can achieve cross-domain .
Realization principle : Both pages passed js Force settings document.domain Is the base primary domain , I'm going to implement the same domain .
location.hash + iframe Cross domain
Realization principle : a with b Cross-domain communication , Through the middle page c To achieve . Three pages , Between domains iframe Of location.hash Pass value , Direct between the same fields js Access to communicate .
Concrete realization :A Domain :a.html -> B Domain :b.html -> A Domain :c.html,a And b Different domains can only pass through hash Value one way communication ,b And c Different domains can only communicate one way , but c And a The same domain , therefore c It can be done by parent.parent visit a All objects on the page .
<iframe id="iframe" src="http://www.domain2.com/b.html" style="display:none;"></iframe>
<script>
var iframe = document.getElementById('iframe');
// towards b.html Pass on hash value
setTimeout(function() {
iframe.src = iframe.src + '#user=admin';
}, 1000);
// Open to codomain c.html The callback method
function onCallback(res) {
alert('data from c.html ---> ' + res);
}
</script>
window.name + iframe Cross domain
window.name Unique attributes :name Values on different pages ( Even different domains ) It still exists after loading , And can support very long name value (2MB).
adopt iframe Of src Property from outland to local region , Cross-domain data is defined by iframe Of window.name From outland to local area . This neatly circumvents the browser's cross-domain access restrictions , But it's also a safe operation .
var proxy = function(url, callback) {
var state = 0;
var iframe = document.createElement('iframe');
// Load the cross-domain page
iframe.src = url;
// onload Events will trigger 2 Time , The first 1 Load the cross-domain page , And keep the data window.name
iframe.onload = function() {
if (state === 1) {
// The first 2 Time onload( The same domain proxy page ) After success , Read the same domain window.name Data in the
callback(iframe.contentWindow.name);
destoryFrame();
} else if (state === 0) {
// The first 1 Time onload( Cross-domain pages ) After success , Switch to the same domain proxy page
iframe.contentWindow.location = 'http://www.domain1.com/proxy.html';
state = 1;
}
};
document.body.appendChild(iframe);
// Get the data and destroy this iframe, Free memory ; This also ensures safety ( Not by other domains frame js visit )
function destoryFrame() {
iframe.contentWindow.document.write('');
iframe.contentWindow.close();
document.body.removeChild(iframe);
}
};
// Request cross-domain b The page data
proxy('http://www.domain2.com/b.html', function(data){
alert(data);
});
postMessage Cross domain
postMessage yes HTML5 XMLHttpRequest Level 2 Medium API, And is one of the few that can operate across domains window One of the attributes , It can be used to solve the following problems :
Data transfer for the page and the new window it opens
Message passing between multiple Windows
Page with nested iframe The messaging
Cross domain data transfer for the above three scenarios
otherWindow: A reference to another window , such as iframe Of contentWindow attribute 、 perform window.open Window object returned 、 Or named or indexed window.frames.
message: Will be sent to others window The data of .
targetOrigin: windowed origin Property to specify which Windows can receive message events .
transfer( Optional ) : It is a list of and message Simultaneous transitive Transferable object . Ownership of these objects is transferred to the recipient of the message , The sender will no longer retain ownership
<iframe id="iframe" src="http://www.domain2.com/b.html" style="display:none;"></iframe>
<script>
var iframe = document.getElementById('iframe');
iframe.onload = function() {
var data = {
name: 'aym'
};
// towards domain2 Transfer cross-domain data
iframe.contentWindow.postMessage(JSON.stringify(data), 'http://www.domain2.com');
};
// Accept domain2 Return the data
window.addEventListener('message', function(e) {
alert('data from domain2 ---> ' + e.data);
}, false);
</script>
<script>
// receive domain1 The data of
window.addEventListener('message', function(e) {
alert('data from domain1 ---> ' + e.data);
var data = JSON.parse(e.data);
if (data) {
data.number = 16;
// Deal with it and send it back domain1
window.parent.postMessage(JSON.stringify(data), 'http://www.domain1.com');
}
}, false);
</script>
WebSocket Protocol cross domain
principle : This approach is essentially unused HTTP Response header for , Therefore, there is no cross domain restriction .
WebSocket protocol yes HTML5 A new agreement . It realizes full duplex communication between browser and server , At the same time, cross domain communication is allowed , yes server push A good implementation of Technology .
Between the web browser and the server “ Socket ” Connect . In short : There is a persistent connection between the client and the server , And both sides can start sending data at any time .
<script>
let socket = new WebSocket("ws://localhost:8080");
socket.onopen = function() {
socket.send("holle");
};
socket.onmessage = function(e) {
console.log(e.data);
};
</script>
const WebSocket = require("ws");
const server = new WebSocket.Server({
port: 8080 });
server.on("connection", function(socket) {
socket.on("message", function(data) {
socket.send(data);
});
});
The browser opens cross domain
In fact, the cross domain problem is the browser policy , The source is him , Turn this off
Windows
Find the directory where you installed
.\Google\Chrome\Application\chrome.exe --disable-web-security --user-data-dir=xxxx
1
Mac
~/Downloads/chrome-data This directory can be customized .
/Applications/Google\ Chrome\ Canary.app/Contents/MacOS/Google\ Chrome\ Canary --disable-web-
What is the homology strategy preventing
Cross domain only exists on the browser side . The browser is web Provide access to . We can open many pages in the browser . It is such an open form , So we need to limit him . For example, the forest is big , All kinds of birds , We need to have a unified specification for agreement to ensure this security .
No homologous request , prevent JavaScript Various requests of the code for non homologous pages (CSRF attack )
For example, user login a Website , At the same time, it is newly opened tab Open the b Website , If you don't restrict homology , b Can be like a The website makes any request , Will give lawless elements an opportunity to take advantage of .
Limit dom operation , For other pages DOM Elements ( Usually contains sensitive information , such as input label ) The read ()
边栏推荐
- UI consistency design of products
- 路灯照明物联网技术方案,ESP32-S3芯片通信应用,智能WiFi远程控制
- [MySQL] MySQL installation
- The memory four area model of C language program
- JSP implementation of bank counter business performance evaluation system
- JSP实现银柜台业务绩效考核系统
- 根据变换矩阵进行图像拼接
- Implementation of fitness club management system based on SSH
- Mysql主从搭建与Django实现读写分离
- 关于线程池需要注意的几点
猜你喜欢

怎样拥有心灵的平和?获得一颗全新的心灵

Smart panel WiFi linkage technology, esp32 wireless chip module, Internet of things WiFi communication application

SQL safe backup display and zoom font support

Mongodb essence summary

【C语言】程序的内存四区模型

Brief introduction to 44 official cases of vrtk3.3 (combined with steamvr)

The solution to the error "xxx.pri has modification time XXXX s in the futrue" in the compilation of domestic Kirin QT

【C语言】变量本质分析
![[C language] analysis of variable essence](/img/b4/13a5800f2c960ec590c9f7480b09d0.png)
[C language] analysis of variable essence
![[official testerhome] MTSC 2021 Shanghai and Shenzhen PPT download addresses](/img/a0/d1170b20d01a7a586d8ff68279f1d4.jpg)
[official testerhome] MTSC 2021 Shanghai and Shenzhen PPT download addresses
随机推荐
E-commerce middle office system architecture
Mongodb essence summary
Drop down menu dropdown yyds dry inventory of semantic UI
【C语言】封装接口(加减乘除)
【C语言】程序的内存四区模型
The road of global evolution of vivo global mall -- multilingual solution
成功解决:WARNING: There was an error checking the latest version of pip.
树莓派4B使用Intel Movidius NCS 2来进行推断加速
Goodbye to excel and PPT, I found a better visual fool software
关于 国产麒麟Qt编译报错“xxx.pri has modification time xxxx s in the futrue“ 的解决方法
魏武帝 太祖知不可匡正,遂不复献言
数据库新建表,以前没问题的,今天
[data recovery in North Asia] data recovery in which the logical volume of the server is changed and the file system is damaged due to system reinstallation
[automation] generate xlsx report based on openstack automated patrol deployed by kolla
2.28 (defect filling) data type conversion exception handling part multi threading
後續版本是否會支持代碼塊搜索高亮顯示
PostgreSQL basic introduction and deployment
Page crash handling method
R语言使用survival包的coxph函数构建cox回归模型、使用ggrisk包的ggrisk函数可视化Cox回归的风险评分图(风险得分图)、并解读风险评分图、基于LIRI数据集(基因数据集)
19.tornado项目之优化数据库查询