当前位置:网站首页>Resolve cross domain
Resolve cross domain
2022-06-28 04:15:00 【weixin_ forty-seven million one hundred and sixty-four thousand】
. Cross domain solutions
Several mainstream cross domain solutions
1.JSONP To deal with cross domain
- principle :
jsonp It is a means of cross domain communication , Its principle is very simple :
a: The first is to make use of script Labeled src Property to achieve cross domain .
b: By passing the front-end method as a parameter to the server , Then the server side injects the parameters and returns , Realize the communication between the server and the client .
c: Due to the use script Labeled src attribute , So we only support get Method
2. Realization way :
// establish script label
function createScript(){
// Define a script label
let oScript = document.createElement("script");
//script Of src attribute Directly assign values to the interface links that need to be cross domain
// And define callback Parameters , Followed by a callback function
oScript.src = `https://api.asilu.com/today?callback=getTodays`;
// The generated script Added to our dom in
document.body.appendChild(oScript);
}
12345678910
//callback Function for
function getTodays(data) {
// Get the object data obtained across domains
let oTodays = data.data;
}
The above is through jsonp Implements a cross domain request , Get weather data . Since it's called jsonp, Obviously, the purpose is json, And cross domain acquisition , utilize js Create a script label , hold json Of url Assign to script Of scr attribute , Put this script Insert into the page , Let the browser get resources across domains ,callback It's a callback method for page existence , Parameters are what you want json, The callback method should comply with the agreement of the server. Generally, it uses callback perhaps cb, Special note jsonp Only aim at get Formal request
3. Advantages and disadvantages
advantage : Easy to use , No compatibility issues .
shortcoming :
Only support GET request .
The front and rear ends need to be matched .
Because the code is loaded from other fields, the execution , So if other domains are not secure , It's likely that some malicious code will be included in the response .
2.CORS Cross-domain resource sharing (xhr2)
1. principle
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 - 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 - Realization CORS The key to communication is the server , As long as the server realizes CORS Interface , You can communicate across sources
2. Realization
Realization CORS It is not difficult to , Just make some settings on the server : Such as
// Control the allowed request sources
header("Access-Control-Allow-Origin:*"); // * Indicates that any source is allowed Basically, you can set this
// in addition , There are still some settings put request delete Requested , There is also a custom request header ,nodejs The default is get,post
// Control allowed custom request headers
'Access-Control-Allow-Headers': 'abc,efg',
// Control how requests are allowed
'Access-Control-Allow-Methods': 'GET,POST,PUT,PATCH,DELETE'
Be careful :IE10 The following is not supported CORS
3. Advantages and disadvantages
advantage :
CORS Correspondence and homology AJAX There is no difference in communication , The code is exactly the same , Easy to maintain .
Support all types HTTP request .
shortcoming
There are compatibility issues , especially IE10 The following browsers .
When a non simple request is sent for the first time, there will be one more request .
3. Server proxy cross domain
1. principle :
Request through the server language proxy . Such as PHP,C# The server language has no cross domain restrictions .- Let the server go to another website to get the content and then return to the page . Because the same origin policy is a security restriction for browsers . There is no cross domain problem with the server , Therefore, the server can request the resources of the desired domain and return them to the client .
When we request data from a third party , Through the browser ajax It must not be possible to ask , Because people won't set it for you cors, So our server proxy solution to cross domain problem arises at the historic moment .
2. Realization
I'm going through nodejs+express Implement service proxy across domains
Middleware needs to be installed http-proxy-middleware
$ npm install http-proxy-middle
Server code
// Solve cross domain problems through agents
/** * Use nodejs Start a proxy service * A third party http-proxy-middleware middleware */
// introduce express
const express = require('express');
// Introduce agent middleware
const {
createProxyMiddleware } = require('http-proxy-middleware');
// Statement express example
const app = express();
// Sign up for a cors Middleware , Allow cross-domain
app.use((req, res, next) => {
res.set({
// Allow all domain requests , In development ,* It needs to be changed to the corresponding domain name
'Access-Control-Allow-Origin': '*',
// Set the custom request headers that the front end is allowed to pass
'Access-Control-Allow-Headers': 'token',
// Set the allowed request mode
'Access-Control-Allow-Methods': 'GET,POST,PUT,PATCH,DELETE'
});
// Must write , Give control to the next
next();
});
// Register a proxy middleware
// Front end services :http://localhost:8080
// Agency service :http://localhost:3000
// The target service :http://m.maoyan.com
app.use('/api', createProxyMiddleware({
// configuration option
// Destination address : Just the protocol and the host
target: "http://m.maoyan.com",
/** * The path to rewrite * * When we access the target interface through a proxy, the process is roughly as follows * http://localhost:8080 -> request -> * http://localhost:3000/api/ajax/movieOnInfoList -> Proxy to -> * http://m.maoyan.com/api/ajax/movieOnInfoList * At this time, the real target interface address does not exist /api This prefix is . Therefore, the request will fail 404 Other questions * * After setting the following path rewrite rules , The process is as follows * http://localhost:8080 -> request -> * http://localhost:3000/api/ajax/movieOnInfoList -> Proxy to -> * http://m.maoyan.com/ajax/movieOnInfoList */
pathRewrite: {
"^/api": ""
},
// Virtual hosting sites require , Generally, it is directly set to true Just fine
changeOrigin: true
}));
// monitor 3000 port , Start the service
app.listen(3000, () => {
console.log(" Agent service started successfully ");
});
The front-end code
<script>
$(function () {
$.ajax({
url: 'http://localhost:3000/api/ajax/movieOnInfoList',
type: 'GET',
success: function (res) {
console.log(res)
}
})
})
</script>
边栏推荐
- 歐洲家具EN 597-1 跟EN 597-2兩個阻燃標准一樣嗎?
- MSC 307(88) (2010 FTPC Code) Part 9床上用品试验
- 揭开SSL的神秘面纱,了解如何用SSL保护数据
- 美创入选“2022 CCIA中国网络安全竞争力50强”榜单
- 04 summary of various query operations and aggregation operations of mongodb
- Talking about cloud primitiveness, we have to talk about containers
- 05 MongoDB对列的各种操作总结
- Particle theory of light (photoelectric effect / Compton effect)
- leetcode - 329. 矩阵中的最长递增路径
- 机器学习入门笔记
猜你喜欢

From zero to one, I will teach you to build a "search by text and map" search service (I)

政策利好,20多省市开启元宇宙发展规划

关于 SY8120I 的DC-DC的降压芯片的学习(12V降至3.3V)

Digital promising, easy to reach, Huawei accelerates the layout of the commercial market with "five pole" star products

applicationContext. Getbeansoftype obtains the execution methods of all implementation classes under an interface or obtains the operation application scenarios such as implementation class objects. L

first. Net core MVC project

Visualization of loss using tensorboard

In the era of video explosion, who is supporting the high-speed operation of video ecological network?

@Several scenarios of transactional failure

Chapter 1 Introduction to bash
随机推荐
Are the two flame retardant standards of European furniture en 597-1 and en 597-2 the same?
有大佬出现过mysql cdc用 datastream时,出现重复binlog消息的情况吗
MySQL master-slave replication, separation and resolution
Go language -select statement
11_ Deliberate practice and elaboration
leetcode:714. 买卖股票的最佳时机含手续费【dp双状态】
Introversion, lying flat and midlife crisis
Building a server monitoring platform with telegraf influxdb grafana
政策利好,20多省市开启元宇宙发展规划
Simple factory mode
Lingge leangoo agile Kanban tool adds the functions of exporting card documents and pasting shared brain map nodes
leetcode:714. The best time to buy and sell stocks includes handling fee [DP dual status]
GO语言-select语句
AS 3744.1标准中提及ISO8191测试,两者测试一样吗?
CDC全量抽取mysql数据时,怎么才能加快ChunkSplitter呢?
等保三级密码复杂度是多少?多久更换一次?
抖音实战~取关博主
[MySQL] multi table connection query
第一个.net core MVC项目
Using elk to build a log analysis system (I) -- component introduction