Front-end and back-end cross-domain solutions

1. Why there are cross-domain problems

跨域问题是由于浏览器的同源策略导致的. The same-origin policy is a security policy that restricts how documents or scripts from one origin can interact with resources from another origin. The same origin means that the protocols, domain names, and port numbers are all the same. For example, if a page loads a piece of JavaScript code from http://www.example.com, then the page can only interact with resources of the same origin as http://www.example.com, but not with resources of other domain names to interact.

In the development mode where the front-end and back-end are separated, the front-end code usually runs under an independent domain name, while the back-end interface runs under another independent domain name. At this time, due to the restrictions of the same-origin policy of the browser, the front-end code cannot directly access the back-end interface, which leads to cross-domain problems.

For example, when using Ajax in the front-end code to request the back-end interface, if the front-end code and the back-end interface are not under the same domain name, the 浏览器就会阻止这种跨域请求request will fail. In order to solve the cross-domain problem, some means are needed to bypass the same-origin policy of the browser, such as using JSONP, CORS, proxy server and other cross-domain solutions.

2. What are the solutions to cross-domain solutions?

  1. JSONP: Add a script tag to the front-end page to load a JavaScript file under another domain name. Since the callback function of JSONP is executed in the global scope, data can be directly manipulated in the callback function. However, JSONP only supports GET requests and does not support other request methods such as POST.
  2. CORS (Cross-Origin Resource Sharing): CORS is a cross-domain solution, which is a W3C standard and uses the 在服务器端设置响应头中的Access-Control-Allow-Originfield to tell the browser whether to allow cross-domain access. CORS supports various types of HTTP request methods and is more flexible than JSONP.
  3. Proxy server: Set up a proxy server between the front-end page and the back-end interface, 前端页面向代理服务器发送请求,代理服务器再将请求转发到后端接口and the proxy server adds the Access-Control-Allow-Origin header in the response, thereby bypassing the same-origin policy of the browser.
  4. WebSocket: WebSocket is a full-duplex communication protocol that can establish a persistent connection between the client and the server, on which both parties can send or receive data at any time. The WebSocket protocol is not restricted by the same-origin policy, so it can communicate across domains.
  5. postMessage: You can use the postMessage API provided in HTML5 to transfer data between different windows, even if these windows come from different sources, you can also achieve cross-domain communication.

In short, different cross-domain scenarios may require different solutions, and an appropriate cross-domain solution needs to be selected according to the specific situation.

3. What is the best solution to cross-domain

前后端解决跨域的最佳方案是使用 CORS(Cross-Origin Resource Sharing) cross-domain resource sharing protocol. CORS is a cross-domain solution, which tells the browser whether to allow cross-domain access by setting the Access-Control-Allow-Origin field in the response header on the server side. Compared with other cross-domain solutions such as JSONP and proxy servers, CORS has the following advantages:

  • More security. Using other cross-domain solutions such as JSONP and proxy servers may have security risks, while using CORS can control which domain names can access the interface by setting the Access-Control-Allow-Origin field in the response header
    , thereby improving security.
  • Simple and easy to use. Compared with other cross-domain solutions, using CORS only needs to set the response header on the server side to easily solve cross-domain problems, and the front-end code does not need to be modified.
  • All types of HTTP requests are supported. Unlike JSONP, which only supports GET requests, CORS supports all types of HTTP requests, including
    GET, POST, PUT, DELETE, PATCH, etc.

The specific steps for using CORS to cross-domain are as follows:

1. Set the Access-Control-Allow-Origin field in the response header on the server side to allow cross-domain access for the specified domain name. For example, setting to allow http://localhost:8080 domain name for cross-domain access:

response.setHeader("Access-Control-Allow-Origin", "http://localhost:8080");

2. Set the Access-Control-Allow-Methods field in the response header on the server side to allow cross-domain access for specified HTTP request methods. For example, to set request methods such as GET, POST, PUT, DELETE, and PATCH to allow cross-domain access:

response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, PATCH");

3. Set the Access-Control-Allow-Headers field in the response header on the server side to allow cross-domain access for specified request headers. For example, to set request headers such as Content-Type and Authorization to allow cross-domain access:

response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");

To sum up, using CORS is the best solution for front-end and back-end solutions to cross-domain problems. It has the advantages of high security, ease of use, and support for all types of HTTP requests, and can meet the needs of most cross-domain scenarios.

4. How to introduce CORS in Spring

Method 1
Add CorsConfigurationSource Bean: In Spring Boot project, CORS can be configured by adding CorsConfigurationSource Bean, for example:

@Configuration
public class CorsConfig {
    
    
    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
    
    
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", corsConfiguration);
        return source;
    }
}

In the above code, we created a CorsConfiguration object, and set allowed all domain names (*), all request headers and all request methods. Then register the CorsConfiguration object to UrlBasedCorsConfigurationSource, and set the path to intercept all requests (/**), and finally return the UrlBasedCorsConfigurationSource object.

Method 2
: Enable CORS configuration: In a Spring Boot project, CORS configuration can be enabled by adding @CrossOrigin annotation or configuring WebMvcConfigurer Bean. For example:
add @CrossOrigin annotation

@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "*", allowedHeaders = "*", methods = {
    
    RequestMethod.GET, RequestMethod.POST})
public class ApiController {
    
    
    // controller code here
}

In the above code, we added the @CrossOrigin annotation to the ApiController class, and set all domain names (*), all request headers, and GET and POST request methods to be allowed.

Method 3
Configure WebMvcConfigurer Bean

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    
    
    @Override
    public void addCorsMappings(CorsRegistry registry) {
    
    
        registry.addMapping("/api/**")
                .allowedOrigins("*")
                .allowedHeaders("*")
                .allowedMethods("GET", "POST");
    }
}

In the above code, we created a WebMvcConfigurer Bean, rewrote the addCorsMappings method, set the request to intercept the /api/** path, and allowed all domain names (*), all request headers, and GET and POST request methods.

Through the above steps, we can use CORS to solve cross-domain problems in the Spring Boot project, so as to realize front-end and back-end data interaction.

Guess you like

Origin blog.csdn.net/weixin_44183847/article/details/129833166