Spring Boot 配置 CORS
以下來自:https://www.cnblogs.com/yuansc/p/9076604.html
1.跨域?
當它請求的一個資源是從一個與它本身提供的第一個資源的不同的域名時,一個資源會發起一個跨域HTTP請求(Cross-site HTTP request)。
2.源?
源[origin]就是協議、域名和端口號。例如:http://www.baidu.com:80這個URL。
3.同源?
若地址裏面的協議、域名和端口號均相同則屬於同源。
4.跨域實質上
就是受前面所講的瀏覽器同源策略的影響,不是同源的腳本不能操作其他源下面的對象。想要操作另一個源下的對象就需要跨域。 在同源策略的限制下,非同源的網站之間不能發送 AJAX 請求。
5不受同源策略影響
1.頁面中的鏈接,重定向以及表單提交是不會受到同源策略限制的;
2.跨域資源的引入是可以的。但是JS不能讀寫加載的內容。如嵌入到頁面中的“<script src="..."></script>,<img>,<link>,<iframe>”
等。.
6.如何跨域?
1.降域
2.jsonp跨域
2.cors跨域
7.springboot配置cors跨域
**對某一接口配置,可以在方法上添加 @CrossOrigin 註解 **
@CrossOrigin(origins = {"http://localhost:9000", "null"})
@RequestMapping(value = "/test", method = RequestMethod.GET)
public String greetings() {
return "{\"project\":\"just a test\"}";
}
對一系列接口配置,在類上加註解,對此類的所有接口有效
@CrossOrigin(origins = {"http://localhost:9000", "null"})
@RestController
@SpringBootApplication
public class SpringBootCorsTestApplication {
}
如果想添加全局配置,則需要添加一個配置類
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
.maxAge(3600)
.allowCredentials(true);
}
}
還可以通過添加 Filter 的方式,配置 CORS 規則,並手動指定對哪些接口有效
@Bean
public FilterRegistrationBean corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true); config.addAllowedOrigin("http://localhost:9000");
config.addAllowedOrigin("null");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config); // CORS 配置對所有接口都有效
FilterRegistrationBean bean = newFilterRegistrationBean(new CorsFilter(source));
bean.setOrder(0);
return bean;
}