当前位置:网站首页>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:8080http://192.162.2.2:8080 There is a cross domain IP Different
http://192.162.1.1:8080http://192.162.1.1:8081 There is a cross domain Different ports
http://192.162.1.1:8080https://192.162.1.1:8080 There is a cross domain Different agreements
http://192.162.1.1:8080http://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 ;

  1. 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
  2. function jar package java -jar kexuekt01.jar, Or through idea open kexuekt01 project , – Start project
  3. 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 `:
    file

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

  1. jsonp
  2. Inside HttpClient The remote invocation
  3. nginx Reverse proxy
  4. Set the response header to allow cross domain response.setHeader(“Access-Control-Allow-Origin”, “*”);
  5. 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

  1. The background needs to receive jsonp:"callback" Medium "callback" Parameters ,
  2. 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 .
file

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”, “*”);

原网站

版权声明
本文为[Qi_ z]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/177/202206260551185589.html