SpringBoot-Solve the cross-domain request problem

In project development, front-end and back-end separation is becoming more and more popular, but there will be a cross-domain problem when the front-end and back-end separation is accessed through Ajax. That is, due to the security restrictions of the browser, AJAX is not allowed to access data interfaces with different protocols, different domain names, and different port numbers. Otherwise, the No'Access-Control-Allow-Origin' header is present on the requested resource . error will be reported  . As follows:

 The powerful Spring Boot  supports the setting of  CORS (Cross-Origin Resource Sharing) to solve the problem of cross-domain requests. Specifically, the configuration can be done in the following several ways, we can choose one.

1. By way of annotations

(1) Add the annotation @CrossOrigin to the request method to  indicate that this method supports cross-domain

@Controller
public class UserController {

    @GetMapping("/user")
    @ResponseBody
    @CrossOrigin
    public User user(){
        User user = new User();
        user.setPassword("123456");
        user.setUsername("admin");
        user.setRegister(LocalDateTime.now());
        return user;
    }
}

(2) Add the annotation @CrossOrigin  to the control class , which is equivalent to that all methods support cross-domain,

@Controller
@CrossOrigin
public class UserController {

    @GetMapping("/user")
    @ResponseBody
    public User user(){
        User user = new User();
        user.setPassword("123456");
        user.setUsername("admin");
        user.setRegister(LocalDateTime.now());
        return user;
    }
}

(3) @CrossOrigin  annotation parameter configuration:

  • value: indicates the supported domain. This means that requests from the http://localhost:8081 domain support cross-domain. The default is *, which means all domains are available.
  • maxAge: Indicates the validity period of the probe request (advanced judgment is valid). The probe request does not need to be sent every time, and a validity period can be configured. The probe request will be sent after the validity period expires. The default is 1800 seconds, which is 30 minutes.
  • allowedHeaders: Represents allowed request headers. The default is *, which means that all requests in the domain are allowed.

2. Global configuration

(1) Add a custom class to implement the  WebMvcConfigurer  interface, and then implement the addCorsMappings  method in the interface  . As follows:

@Configuration
public class CrosConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedHeaders("*")
                .allowedMethods("*")
                .maxAge(1800)
                .allowedOrigins("*");
    }
}

Description:

  • addMapping: Indicates which format of the request path is cross-domain processing.
  • allowedHeaders: Represents allowed request headers, all request headers are allowed by default.
  • allowedMethods: indicates the allowed request methods, the default is GET, POST and HEAD. The configuration as * here means that all request methods are supported.
  • maxAge: indicates the validity period of the probe request
  • allowedOrigins indicates the supported domains

(2) By adding a global CorsFilter  filter, as shown below:


@Configuration
public class CrosConfig {

    @Bean
    @Order(Integer.MAX_VALUE - 1)
    public CorsFilter corsFilter() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*"); // 允许任何域名使用
        corsConfiguration.addAllowedHeader("*"); // 允许任何头
        corsConfiguration.addAllowedMethod("*"); // 允许任何方法(post、get等)
        corsConfiguration.setAllowCredentials(true); //允许跨域传输所有的header参数
        UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
        configSource.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(configSource);
    }

}

 

Guess you like

Origin blog.csdn.net/small_love/article/details/111744308