Solutions to cross domain problems

​1. What is cross domain?
When any of the protocol, domain name and port of a page request url is different from the current page url, it is cross domain. for instance:

Current page urlRequested page urlCross domainreason
http://www.yzfree.com/http://www.yzfree.com/index.htmlnoHomology (same protocol, domain name and port number)
http://www.yzfree.com/https://www.yzfree.com/index.htmlCross domainDifferent protocols (http/https)
http://www.yzfree.com/http://www.baidu.com/Cross domainDifferent primary domain names (yzfree/baidu)
http://www.yzfree.com/http://blog.yzfree.com/Cross domainDifferent subdomains (www/blog)
http://www.yzfree.com:8080/http://www.yzfree.com:8089/Cross domainDifferent port numbers (8080 / 8089)

2. Why do cross domain problems occur
The cross domain problem is due to the restriction of the Same origin policy of the browser. The Same origin policy is a kind of agreement. It is an implementation of the browser's security function. Without the Same origin policy, the browser is vulnerable to XSS, CSFR and other network attacks.

3. What problems will cross domain lead to
Cookie s, LocalStorage and other data in non homologous web pages cannot be read
You cannot touch the DOM structure of non homologous web pages
AJAX requests cannot be sent to non homologous addresses
Cross domain phenomenon:

Note: html has some special tags, such as < img > < script > < link > < frame >, which has cross domain characteristics. It can directly access non homologous addresses and can be used safely.

4. Solutions to cross domain problems
4.1 JSONP

The way of JSONP is to remotely obtain and execute js code by adding a script element.
The whole logic is: the front end sends a request to the server and specifies the callback function as: test, the back end returns the js code "test(110)", and the front end receives and executes it
Note: this method only supports get requests.

① Native implementation:

<script src="http://yzfree.com/v1?callback=test"></script>
<script type="text/javascript">
    function test(res){
        console.log(res.data);
    }
</script>

② jQuery ajax:

$.ajax({
    url: 'http://yzfree.com/v1',
    type: 'get',
    dataType: 'jsonp', 
    jsonpCallback: "test", 
    data: {}
});
③ Vue.js
this.$http.jsonp('http://yzfree.com/v1', {
    params: {},
    jsonp: 'test'
}).then((res) => {
    console.log(res); 
})

4.2 CORS

The cross origin resource sharing method of CORS is that each page needs to return an http header named access control allow origin to allow non homologous sites to access
Generally, the request only needs to set access control allow origin on the server side. If it is a cross domain request with cookie s, the front and back ends should be set
[front end]

① Native ajax

var xhr = new XMLHttpRequest();
// Set whether cookie s can be carried
xhr.withCredentials = true;
​
xhr.open('post', 'http://yzfree.com/v1', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send('user=gwx');
​
xhr.onreadystatechange = function() {
    if (xhr.readyState == 4 && xhr.status == 200) {
        alert(xhr.responseText);
    }
};

② jQuery ajax

$.ajax({
   url: 'http://yzfree.com/v1',
   type: 'get'
  data: {}
  xhrFields: 
      // Set whether cookie s can be carried
      withCredentials: true
  }
})


③vue-resource

// Set whether cookie s can be carried
Vue.http.options.credentials = true

④ axios

// Set whether cookie s can be carried
axios.defaults.withCredentials = true

[back end SpringBoot]
When the server responds to the client, bring access control allow origin
① Use @ CrossOrigin annotation

@RequestMapping("/v1")
@RestController
//@CrossOrigin / / you can access any domain without limiting the specified domain name
@CrossOrigin("https://yzfree.com ") / / specify the domain name
public class CorsTestController {
    @GetMapping("/test")
    public String sayHello() {
        return "success";
    }
}

② CORS global configuration

@Configuration
public class CorsConfig {
    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*"); // Allow any domain name
        corsConfiguration.addAllowedHeader("*"); // Allow any header
        corsConfiguration.addAllowedMethod("*"); // Allow any method (post, get, etc.)
        return corsConfiguration;
    }
​
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig()); 
        return new CorsFilter(source);
    }
}

③ Interceptor implementation

@Component
public class CorsFilter implements Filter {
​
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletResponse res = (HttpServletResponse) response;
        res.addHeader("Access-Control-Allow-Credentials", "true");
        res.addHeader("Access-Control-Allow-Origin", "*");
        res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
        res.addHeader("Access-Control-Allow-Headers", "Content-Type,X-CAF-Authorization-Token,sessionToken,X-TOKEN");
        if (((HttpServletRequest) request).getMethod().equals("OPTIONS")) {
            response.getWriter().println("ok");
            return;
        }
        chain.doFilter(request, response);
    }
    @Override
    public void destroy() {
    }
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
}

4.3 proxy

Implemented through middleware, the browser has cross domain restrictions, but the server does not. If changeOrigin is set to true, a local virtual node server will receive your request and forward it

proxyTable: {
 '/api': {
  target: 'Destination address', //Destination address
  changeOrigin: true, //Cross domain
  pathRewrite: {
   '^/api': '' //Path rewriting
   }
 }
}
​

//Using axios
 this.$axios.post("/api/gwx",{
   Data sent
  }).then(data=>{
   console.log(data);
  })

4.4 nginx reverse proxy

By modifying nginx Conf configuration file as proxy forwarding

server {
    listen 80;
    server_name www.yzfree.com;
​
 location ^~/gwx/ {
            proxy_pass http://xxx.com:80;// The address you want to forward
            proxy_set_header Host $host:$server_port;
            proxy_set_header Remote_Addr $remote_addr;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            client_max_body_size    2048m;
        }

The above are several common cross domain solutions.

Added by Sprout on Sat, 29 Jan 2022 14:33:41 +0200