Spring boot summarizes the cross-origin cors method, springcors
Background
Many of the projects we are working on are separated from the frontend and backend, which leads to a very common problem. Our pages and interfaces are under different domain names, cross-origin issues occur when we access backend interfaces through ajax. How can we solve this problem? Generally, cors and jsonp are used. Spring simplifies cors configuration. Let's take a look at the cors provided by Spring.
Cross-origin Problem Description
Cross-origin problems are often encountered in Web development. The solutions include jsonp, iframe, and CORS.
CORS compared with JSONP:
1. JSONP can only implement GET requests, while CORS supports all types of HTTP requests.
2. With CORS, developers can use common XMLHttpRequest to initiate requests and obtain data, which provides better error handling than JSONP.
3. JSONP is mainly supported by old browsers, which often do not support CORS, and most modern browsers already support CORS.
WebMvcConfigurer object
We can initialize a WebMvcConfigurer object to configure our cors ing.
@ Configurationpublic class CorsCongiguration {@ Bean public WebMvcConfigurer corsConfigurer () {return new WebMvcConfigurerAdapter () {@ Override public void addCorsMappings (CorsRegistry registry) {registry. addMapping ("/api/**"); // allow all third-party domain names to access this interface //. allowedOrigins ("http://domain2.com") // specify the source domain name //. allowedMethods ("PUT", "DELETE ")//. allowedHeaders ("header1", "header2", "header3 ")//. exposedHeaders ("header1", "header2 ")//. allowCredentials (false ). maxAge (3600 );}};}}
Inherit WebMvcConfigurerAdapter
This method is similar to the above method.
@Configuration@EnableWebMvcpublic class CorsConfiguration_2 extends WebMvcConfigurerAdapter { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/api/**"); }}
CorsFilter
This method is rarely used now
@ Component @ EnableWebMvcpublic class extends CorsFilter {public CorsFilterCongiguration (CorsConfigurationSource configSource) {super (configSource);} @ Bean public FilterRegistrationBean corsFilter () {partition source = new partition (); corsConfiguration config = new CorsConfiguration (); config. setAllowCredentials (true); config. addAllowedOrigin ("*"); // config. addAllowedOrigin ("http://domain1.com"); config. addAllowedHeader ("*"); config. addAllowedMethod ("*"); source. registerCorsConfiguration ("/api/**", config); FilterRegistrationBean bean = new FilterRegistrationBean (new CorsFilter (source); bean. setOrder (0); // return bean before all filters ;}}
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.