CORS :Cross-Origin Resource Sharing 跨域资源共享
跨域:只要协议、域名、端口 三者有任何一个不同即为跨域
就像localhost和127.0.0.1 就是两个不同的域名
所以http://localhost:8081/find_by_id?video_id=2
和http://127.0.0.1:8081/find_by_id?video_id=2 就形成跨域
CORS使用一些HTTP头信息——包括请求和返回
Access-Control-Allow-Origin:访问控制允许源,*表示任意域名
response.setHeader("Access-Control-Allow-Origin","https://example.com");
Access-Control-Allow-Credentials:访问控制允许凭据
它的值只有一个就是 true。跨站点带验证信息时,服务器必须要争取设置这个值,服务器才能获取到用户的cookie。
Access-Control-Allow-Headers
提供一个逗号分隔的列表,表示服务器支持的请求数据类型。
假如你使用自定义头部(比如:x-authentication-token
服务器需要在返回OPTIONS请求时,要把这个值放到这个头部里,否则请求会被阻止)。
Access-Control-Allow-Methods
一个逗号分隔的列表,表明服务器支持的请求类型(比如:GET, POST,PUT,DELETE,HEAD,OPTIONS)
Access-Control-Expose-Headers
这个返回信息里包含了一组头部信息,这些信息表示哪些客户端可以使用。
其他没有在里面的头部信息将会被限制,比较少用
方式一:
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
/**
* 使用spring 方式
* spring 4.2起,
* 可以使用spring 自带的CorsFilter和@CrossOrgin注解
*/
@Configuration
public class CorsConfig {
@Bean
public FilterRegistrationBean corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
// 设置你要允许的网站域名,*表示任意域名
config.addAllowedOrigin("https://ljh.com");
//
config.addAllowedHeader("*");//* 表示任意头部信息
config.addAllowedMethod("GET, POST,PUT,DELETE,HEAD,OPTIONS");
source.registerCorsConfiguration("/**", config);
FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
// 这个顺序很重要,为避免麻烦请设置在最前
bean.setOrder(0);
return bean;
}
}
方式二:实现WebMvcConfigurer 的addCorsMappings
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* spring boot 方式--全局
* 我认为比较优雅的解决方案
* 针对对某个Controller类或者方法可使用@CrossOrigin注解
*/
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("http://ljh.com")
.allowedMethods("GET,POST,PUT,DELETE,HEAD,OPTIONS")
.allowedHeaders("*")
.allowCredentials(false).maxAge(3600);
}
}