当前位置:网站首页>Five solutions across domains
Five solutions across domains
2022-06-26 06:08:00 【Qi_ z】
For more information, please refer to :
Download notes and related materials of five cross domain solutions
1. What is cross-domain
Browsers are not allowed to execute the footsteps of other websites (ajax), The same origin policy of the browser ;
for example : launch ajax If requested IP、 port 、 The agreement is different , All belong to cross domain .
For example, in the following case ,A Site requires request B Website interface :
| A Website | B Website | Cross domain or not | explain |
|---|---|---|---|
| http://192.162.1.1:8080 | http://192.162.2.2:8080 | There is a cross domain | IP Different |
| http://192.162.1.1:8080 | http://192.162.1.1:8081 | There is a cross domain | Different ports |
| http://192.162.1.1:8080 | https://192.162.1.1:8080 | There is a cross domain | Different agreements |
| http://192.162.1.1:8080 | http://192.162.1.1:8080 | There is no cross domain | ( agreement 、ip、 port ) All the same |
2. Demonstrate cross domain issues
step :
First, download the relevant materials of this chapter in the upper right corner ;
- take demo.html Put in Nginx Of html Directory _( It has been put in by default )_, double-click nginx.exe start-up Nginx, – start-up Nginx
- function jar package
java -jar kexuekt01.jar, Or through idea open kexuekt01 project , – Start project - Browser access :
http://127.0.0.1/demo.html– See the effect
F12 Open the browser console to view the cross domain error error message `:
Important knowledge points : When there is a cross domain Java Interfaces can be used for normal business processing , Only the browser cannot receive the data returned from the background , And in the picture 1 Cross domain error output from browser console .
3. Five ways to solve cross domain
- jsonp
- Inside HttpClient The remote invocation
- nginx Reverse proxy
- Set the response header to allow cross domain response.setHeader(“Access-Control-Allow-Origin”, “*”);
- SpringBoot annotation @CrossOrigin
3.1 Jsonp Solve cross domain demonstration
The front-end code
$.ajax({
type:"get",
dataType:"jsonp",
jsonp:"callback",// Override the name of the callback function in the request
url:"http://127.0.0.1:8080/kexue/user",
success:function (data) {
alert(data.response);
}
}, 'json');
Background code
- The background needs to receive jsonp:"callback" Medium "callback" Parameters ,
- The format of the return parameter must be :callback({object});
@RequestMapping("/kexue/user")
public String demo(String callback) {
JSONObject obj = JSONUtil.createObj();
obj.put("code", 200);
obj.put("response", " Successful call ");
// Returns the format :callback({object});
return callback + "(" + obj + ")";
}
explain
Jsonp It is troublesome to use , This method is generally not used to solve cross domain problems .
3.2 Inside HttpClient The remote invocation
Start two background
port 1:8080( The project of our company has solved the cross domain problem )
port 2:8081( Simulate third-party project interfaces , The cross domain problem is not solved )
8080 Port item
@CrossOrigin // Cross domain annotation
@RestController
public class Demo1 {
@RequestMapping("/kexue/user")
public JSONObject demo() {
String body = HttpRequest.get("127.0.0.1:8081/kexue/user2").execute().body();
JSONObject obj = JSONUtil.parseObj(body);
return obj;
}
}
8081 Port item ( Third party interface )
@RequestMapping("/kexue/user2")
public JSONObject demo() {
JSONObject obj = JSONUtil.createObj();
obj.put("code", 200);
obj.put("response", " Third party interface ");
return obj;
}
notes : Modify port number , To facilitate the test -Dserver.port=8081
explain
HttpClient This method is suitable for calling third-party interfaces .
for example : When calling a third-party interface , If the front end directly calls the third-party interface, a cross domain problem will be reported ( The third-party interface does not solve the cross domain problem ), Then you can only go through the backstage HttpClient To make a call .
3.3 Nginx Reverse proxy
The front-end code
$.ajax({
type:"get",
url:"http://127.0.0.1:80/kexue/user",
success:function (data) {
// Processing after successful request
alert(data.response);
}
}, 'json');
Back end code
@RequestMapping("/kexue/user")
public JSONObject demo() {
JSONObject obj = JSONUtil.createObj();
obj.put("code", 200);
obj.put("response", " Successful call ");
// Returns the format :callback({object});
return obj;
}
nginx.conf
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm;
}
# Intercept all with /kexue Initial request
location /kexue {
index proxy_set_header Host $host;
index proxy_set_header X-Real-IP $remote_addr;
index proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://127.0.0.1:8080; # Back end service address
}
}
}
explain
Use Nginx The premise of direction proxy is , The front-end code (vue) Need and Nginx The service is on a physical machine ; If the above conditions are met , Give priority to passing Nginx Reverse proxy to solve cross domain problems .
3.4 Set the response header to allow cross domain
The front-end code
$.ajax({
type:"get",
url:"http://127.0.0.1:8080/kexue/user",
success:function (data) {
// Processing after successful request
alert(data.response);
}
}, 'json');
Back end code
@RequestMapping("/kexue/user")
public JSONObject demo(HttpServletResponse response) {
JSONObject obj = JSONUtil.createObj();
obj.put("code", 200);
obj.put("response", " Successful call ");
// * Allow all sites to cross domain
response.setHeader("Access-Control-Allow-Origin", "*");
return obj;
}
explain
It is usually configured in the interceptor “ Set the response header to allow cross domain ”.
3.5 @CrossOrigin annotation
The front-end code
$.ajax({
type:"get",
url:"http://127.0.0.1:8080/kexue/user",
success:function (data) {
// Processing after successful request
alert(data.response);
}
}, 'json');
Back end code
@CrossOrigin // Cross domain annotation
@RestController
public class Demo1 {
@RequestMapping("/kexue/user")
public JSONObject demo() {
JSONObject obj = JSONUtil.createObj();
obj.put("code", 200);
obj.put("response", " Successful call ");
return obj;
}
}
explain
@CrossOrigin The bottom layer of the annotation passes Spring The interceptor function of response Add in Access-Control-Allow-Origin Wait for response header information .
response.setHeader(“Access-Control-Allow-Origin”, “*”);
边栏推荐
- Yamaha robot splits visual strings
- Detailed explanation of serial port communication principle 232, 422, 485
- 【群内问题学期汇总】初学者的部分参考问题
- Ribbon load balancing service call
- Deeply uncover Ali (ant financial) technical interview process with preliminary preparation and learning direction
- 小程序第三方微信授权登录的实现
- 花生壳内网穿透映射NPM私服问题
- 解决在win10下cmder无法使用find命令
- MySQL-06
- University Information Management System
猜你喜欢
随机推荐
【 langage c】 stockage des données d'analyse approfondie en mémoire
SQL query time period content
Tencent WXG internship experience (has offered), I hope it will help you!
numpy.log
Redis multithreading and ACL
Typora activation method
On site commissioning - final method of kb4474419 for win7 x64 installation and vs2017 flash back
SQL Server view
The purpose of writing programs is to solve problems
numpy. frombuffer()
机器学习 05:非线性支持向量机
SQL Server 函数
Selective Search for Object Recognition 论文笔记【图片目标分割】
跨域的五种解决方案
MEF framework learning record
[C language] deep analysis of data storage in memory
实时数仓方案如何选型和构建
421-二叉树(226. 翻转二叉树、101. 对称二叉树、104.二叉树的最大深度、222.完全二叉树的节点个数)
Pytorch (network model training)
Machine learning 07: Interpretation of PCA and its sklearn source code









