CORS
全称
Cross-Origin Resource Sharing
Rest应用
实现
- 页面的JavaScript和后端的Rest API互动
限制
概念:同源
- 域名相同
- 端口相同
- 协议相同
javaScript只可以访问同源的REST API
想要访问不同源的API要通过CORS
在网站允许的情况下,通过CORS才能访问成功
设置CORS
使用@CrossOrigin注解
允许特定域名跨域访问
1
2
3
4
5
6
public class ApiController {
...
}允许多个域名跨域访问
1
2
3
4
5
6
public class ApiController {
...
}允许所有域名跨域访问
1
2
3
4
5
6
public class ApiController {
...
}
使用CorsRegistry
在WebMvcConfigurer中定义全局配置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
WebMvcConfigurer createWebMvcConfigurer( { HandlerInterceptor[] interceptors)
return new WebMvcConfigurer() {
public void addInterceptors(InterceptorRegistry registry) {
for (var i : interceptors) {
registry.addInterceptor(i);
}
}
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("/static/");
}
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("\"http://eternalfire.xyz:8080\"")
.allowedMethods("GET", "POST");
}
};
}
使用CorsFilter
- 和配置Filter的方法一样,一样繁琐
测试
用@CrossOrigin(origins = “https://www.baidu.com“) 注解我的REST API:
百度测试:

成功;
京东测试:

报错:origin ‘https://www.jd.com‘ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
