How to implement cross-origin resource sharing in Spring Boot?
There are multiple ways to implement Cross-Origin Resource Sharing (CORS) in Spring Boot, and one commonly used method is as follows:
- Add cross-origin configuration in the configuration class of Spring Boot.
@Configuration
public class CorsConfig {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*") // 允许所有域名访问,也可以指定特定域名
.allowedMethods("GET", "POST", "PUT", "DELETE") // 允许的请求方法
.allowedHeaders("*") // 允许的请求头
.allowCredentials(true) // 是否允许发送 Cookie
.maxAge(3600); // 探测请求的有效期
}
};
}
}
The above code will allow all domains to access and send cookies, and the configuration can be adjusted according to actual needs.
- Use the @CrossOrigin annotation:
By adding the @CrossOrigin annotation to the method in the Controller layer, it is also possible to achieve cross-origin resource sharing, for example:
@RestController
public class MyController {
@CrossOrigin(origins = "*", maxAge = 3600)
@GetMapping("/hello")
public String hello() {
return "Hello, world!";
}
}
These are two common methods used to implement Cross-Origin Resource Sharing. In practical projects, you can choose the most suitable method according to your needs.