SpringBoot解决接口跨域问题

在Spring Boot 2.X应用程序中可以使用注解@CrossOrigin,也可以通过使用WebMvcConfigurer对象来定义全局CORS配置。

  1. @CrossOrigin注解示例代码

 

接口类:HelloController

@RestController
public class HelloController {
@CrossOrigin
@RequestMapping("/hello")
public String HelloSpring (){
    return "解决跨域了";
}

}

  

WebMvcConfigurer对象示例代码

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class MyConfiguration {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/")
.allowedOrigins("
")
.allowCredentials(true)
.allowedMethods("GET", "POST", "DELETE", "PUT","PATCH")
.maxAge(3600);
}
};
}
}

  

posted @ 2021-09-23 16:30  杜嘟嘟  阅读(356)  评论(0)    收藏  举报