当前位置:网站首页>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”, “*”);
边栏推荐
- The use of loops in SQL syntax
- SQL Server 函数
- On site commissioning - final method of kb4474419 for win7 x64 installation and vs2017 flash back
- 【C語言】深度剖析數據在內存中的存儲
- Class and object learning
- SSH keygen specifies the path
- Selective search for object recognition paper notes [image object segmentation]
- 家庭记账程序(第一版)
- Deeply uncover Ali (ant financial) technical interview process with preliminary preparation and learning direction
- Func < T, tresult > Commission - learning record
猜你喜欢
随机推荐
[C language] deep analysis of data storage in memory
Detailed explanation of serial port communication principle 232, 422, 485
MEF framework learning record
力扣 875. 爱吃香蕉的珂珂
Library management system
Thread status and stop
通俗易懂的从IDE说起,再谈谈小程序IDE
类和对象的学习
Hot! 11 popular open source Devops tools in 2021!
Combined mode, transparent mode and secure mode
Tencent's 2022 school recruitment of large factories started with salary, and the general contracting of cabbage is close to 40W!
05. basic data type - Dict
tf.nn.top_k()
花生壳内网穿透映射NPM私服问题
cross entropy loss = log softmax + nll loss
Test depends on abstraction and does not depend on concrete
Level signal and differential signal
Sql语法中循环的使用
Prototype mode, Baa Baa
Redis underlying data structure