当前位置:网站首页>Several solutions to spanning
Several solutions to spanning
2022-07-28 13:59:00 【Maic】
The reason for cross domain is firstly influenced by the security design of the browser , Due to the design of browser homology policy , So cross domain .
In the project , We often encounter cross domain problems , Although in your project , Scaffold has 100% The local agent is ready 、 Or the operation and maintenance old railway is nginx Interface proxy has been made for you in , So the probability of cross domain is much less , But in traditional projects , In that jquery The era of rampant , Or when you take over an ancestral project , Cross domain problems occur from time to time , This article is only for the author to understand the common solutions across domains , I hope I can give you some thought and help in the actual project .
Text begins ...
What is homology
- The agreement is the same
- Domain name is the same
- The same port
Non homologous people cannot access each other cookie,dom operation ,ajax、localStorage、indexDB operation
But non homologous sources can access some of the following properties
window.postMessage();
window.location
window.frames
window.parent
...
For cross domain communication of non homologous websites , We can adopt the following schemes
Fragment identifier
By means of url Put #type, utilize hashchange event , Get the related information of the parent page hash data
// parent
const type = 'list';
const originUrl = originUrl + '#'+type;
const iframe = document.getElementById('iframe');
iframe.src = originUrl;
In the child iframe in , We can monitor hashchange event
// iframe
window.addEventListener('hashchange', (evt) => {
console.log(evt) // Get the relevant data of the fragment identifier
})
Communicate across documents window.postMessage
Subpages can take advantage of window.postMessage Send message to parent page , The parent page listens message Receive messages sent by sub pages , Usually this way in iframe Used more in communication , It is also a solution for cross domain communication
// parent
window.addEventListener('message', (evt) => {
const data = evt.data;
console.log(data)
})
// child
const origin = '*'; // Here is the domain name of the parent page , But it can also be *
const data = {
text: 'hello, world'
};
window.postMessage(data,origin)
jsonp
utilize script label , Send one to the server get request ,url Bind a callback=fn, This fn It is usually well constrained with the back end ,fn Is the name of the function executed by the client .
Use a simple example to explain jsonp
Client example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jsonp</title>
</head>
<body>
<h3>jsonp</h3>
<div id="app"></div>
<script>
var script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.src = 'http://192.168.31.40:8080/api?callback=jsonp';
document.body.appendChild(script);
const renderHtml = ({name, age}, dom) => {
dom.innerHTML = `<div> My name ${name}, This year, ${age} Year old </div>`
}
function jsonp(data) {
console.log(data);
const app = document.getElementById('app');
const {name, age} = data;
renderHtml({name, age}, app)
}
</script>
</body>
</html>
Server sample code
// server.js
const http = require('http');
const fs = require('fs');
const path = require('path');
const PORT = '8080';
const server = http.createServer((req, res) => {
res.statusCode = 200;
// console.log(req.url);
res.setHeader('Content-Type', 'text/html');
fs.readFile(path.resolve(__dirname, '../', 'index.html'), (err, data) => {
if (err) {
res.end('404');
return;
}
res.end(data);
});
const data = {
name: 'Maic',
age: Math.floor(Math.random() * 20)
}
if (req.url.includes('/api')) {
res.end(`jsonp(${JSON.stringify(data)})`)
}
});
server.listen(PORT, () => {
console.log('server is start'+ PORT);
})
Notice that we see a judgment like this req.url.includes('/api'), And then we res.end(jsonp(JSON.stringify(data))), Back to you jsonp This callback function , Send data to the front end as formal parameters , Defined on the client side jsonp Method to get the corresponding data .
perform node server.js open http://localhost:8080 We will find that
The data returned is jsonp({name: 'xx',age: 'xx'})
Let's look at the request header
The browser will send a get request , The parameters carried are callback: jsonp, On the client side, we actually use jsonp This method gets the corresponding data .
So we can know jsonp It is actually sent by a client get Request to carry the return of a back-end service Callback function , On the client side , We define this Callback function You can get the formal parameter data returned by the back end .
from jsonp This kind of cross domain communication , In fact, it has its disadvantages and advantages
- shortcoming
1、 Its security will be at risk , Because the result of the dependency is the formal parameter content of the callback function , If someone hijacks and modifies the returned data , That may cause security problems
2、 Support only get request , Other... Are not supported http Request mode , We found that jsonp This communication is the use of script The tag requested a url,url An executable callback function is carried on the , And then pass data to the callback function through the back end .
3、 There are no status codes , Data is lost to the client , If there is a failure , It won't be like that http The status code is the same
- advantage
It can solve the problem of cross domain communication , Good compatibility , Not affected by homologous strategies , The implementation is also simple for the back end .
In previous projects with a long history , You may be using it directly jquery,jsonp Just ok 了 , The approximate code is like this
$.ajax({
url: 'xxx',
dataType: 'jsonp',
jsonp: 'successCallback',
success: (data) => {
console.log(data)
},
error: (err) => {
console.log(err)
}
})
successCallback This is the callback function constrained by the server , Generally, the communication with the server is consistent , So simple jsonp We're done , Does it feel very simple ?
WebSocket
because WebSocket Not limited by the same origin policy , therefore WebSocket It can also realize cross domain communication . There is no example here , For details, please refer to the previous article Talking about websocket This article
CORS Cross domain resource sharing
This method is used to control the server , Allow any resource requests . In fact, on the browser side , Even across domains , It will still request normally , Just request the back-end service of the non homologous environment , The browser prohibits requesting access , For more information, please refer to this article cors[1]
Let's write an example to test , Add this code to the client
const send = document.getElementById('send');
send.onclick = function () {
if (!window.fetch) {
return;
}
fetch('http://localhost:8081/list.json')
.then((res) => res.json())
.then((result) => {
console.log(result);
const contentDom = document.querySelector('.content');
renderHtml(result, contentDom);
});
};
Server code , We build a new one index2.js Server code , And implement node index2.js
const http = require('http');
const PORT = '8081';
const server = http.createServer((req, res) => {
res.statusCode = 200;
// // console.log(req.url);
res.setHeader('Content-Type', 'application/json');
if (req.url.includes('/list.json')) {
res.end(JSON.stringify({
name: 'maic',
age: Math.ceil(Math.random() * 20)
}));
}
});
server.listen(PORT, () => {
console.log('server is start'+ PORT);
})
We note that the requested port is 8081, open 8080 page
Click button , send out fetch request , We found that the browser reported the cross domain information you often see as been blocked by CORS policy: No 'Access-Control-Allow-Origin' header..., Because it's cross domain
Then we set up the server Access-Control-Allow-Origin: *
const http = require('http');
const PORT = '8081';
const server = http.createServer((req, res) => {
res.statusCode = 200;
// // console.log(req.url);
res.setHeader('Content-Type', 'application/json');
res.setHeader('Access-Control-Allow-Origin', '*');
if (req.url.includes('/list.json')) {
res.end(JSON.stringify({
name: 'maic',
age: Math.ceil(Math.random() * 20)
}));
}
});
server.listen(PORT, () => {
console.log('server is start'+ PORT);
})
When you visit again , already ok 了
Notice that we can look at Response Headers
HTTP/1.1 200 OK
Content-Type: application/json
Access-Control-Allow-Origin: *
Date: Sun, 01 May 2022 14:23:59 GMT
Connection: keep-alive
Content-Length: 24
Access-Control-Allow-Origin:* This is the setting response request header of our service , Set allow all domain name requests .
therefore cors Cross domain is actually set on the server Access-Control-Allow-Origin:* This perfectly solves the cross domain problem .
summary
- The causes of cross domain , Mainly affected by the homology strategy , Non homologous environment , Cannot access each other
cookie、localStorage、dom operationetc. - Cross domain solutions mainly include
Fragment identifier、iframe signal communication postMessage,jsonp、WebSocket、cors - Learn more about several cross domain patterns with specific practical examples , such as
jsonp, It's actually usingscriptSend agetrequest , staygetAn executable callback function is passed in the requested parameters , Service upon request , Will return a callback function that the front end can execute , And take the data as the formal parameter of the callback function , Define the callback function at the front end , So as to obtain the data passed in by the calling function . - Use specific examples to set the server
cors, It is mainly set in the return response header of the back-end interfaceAccess-Control-Allow-Origin:*Allow all websites from different origins to access , This method is also a common means to roughly solve cross domain problems . - Sample code of this article code example[2]
Reference material
[1]cors: https://www.wangdoc.com/javascript/bom/cors.html
[2]code example: https://github.com/maicFir/lessonNote/tree/master/node/jsonp
边栏推荐
- What is the reason why the words behind word disappear when typing? How to solve it?
- DXF读写:标注样式组码中文说明
- 【飞控开发基础教程7】疯壳·开源编队无人机-SPI(气压计数据获取)
- Leetcode depth first and breadth first traversal
- Continuous (integration -- & gt; delivery -- & gt; deployment)
- I'm bald! Who should I choose for unique index or general index?
- 基于NoneBot2的qq机器人配置记录
- Children's programming electronic society graphical programming level examination scratch Level 2 real problem analysis (judgment question) June 2022
- No swagger, what do I use?
- 掌握常见的几种排序-选择排序
猜你喜欢
随机推荐
SAP ui5 fileuploader control realizes local file upload, and trial version of cross domain access error encountered when receiving server-side response
Countdown 2 days! 2022 China Computing Conference: Mobile cloud invites you to meet with computing network for innovative development
IntersectionObserver交叉观察器
数据库系统原理与应用教程(059)—— MySQL 练习题:操作题 1-10(三)
数据库系统原理与应用教程(060)—— MySQL 练习题:操作题 11-20(四)
Poj3275 ranking the cows
Product Manager: job responsibility table
数据库系统原理与应用教程(058)—— MySQL 练习题(二):单选题
I'm bald! Who should I choose for unique index or general index?
R language uses dpois function to generate Poisson distribution density data and plot function to visualize Poisson distribution density data
C language: merge sort
My friend sent me some interview questions
POJ3259虫洞题解
After finishing, help autumn move, I wish you call it an offer harvester
酷炫操作预热!代码实现小星球特效
SLAM论文合集
R语言检验样本比例:使用prop.test函数执行单样本比例检验计算总体中成功样本比例p值的置信区间(设置conf.level参数指定置信水平、置信区间的大小)
国产API管理工具Eolink太好用了,打造高效的研发利器
Strict mode -- let and const -- arrow function -- Deconstruction assignment -- string template symbol -- set and map -- generator function
Vite configuring path aliases in the project







