Spring Boot提供了一些配置来处理跨域问题。下面是几种解决跨域问题的方法:
使用Spring Security:
@Configuration@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http // ...
.cors().and().csrf().disable();
}
}
自定义过滤器:
@Component
public class CorsFilter implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
HttpServletRequest request = (HttpServletRequest) req;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
chain.doFilter(req, res);
}
}
将自定义过滤器添加到Spring Boot应用程序的配置中。
#application.properties
spring.mvc.cors.allowed-origins=http://example.com,http://sub.example.comspring.mvc.cors.allowed-methods=GET,POST,PUT,DELETE,OPTIONS
spring.mvc.cors.allowed-headers=X-Requested-With,Content-Type,Origin,Access-Control-Request-Method,Access-Control-Request-Headersspring.mvc.cors.max-age=3600
例如:
@RestController
@CrossOrigin(origins = "http://example.com")
public class MyController {
}