关于跨域资源共享(CORS):https://www.cnblogs.com/loveis715/p/4592246.html,它能防止js代码跨域操作。

例如,你的web应用占用8080端口,并且通过js代码你尝试访问9090端口的服务,在这样的条件下,你的浏览器会报CORS错误,为了解决这样的错误,需要以下两个条件:
- RESTful Web服务应该支持跨域资源共享
- RESTful Web服务应该允许从8080端口访问API
在这个章节,我们将详细学习怎么让RESTful Web Service 允许Cross-Origin请求
Enable CORS in Controller Method
我们需要在RESTful Web 服务上使用@CrossOrigin注解标注控制器方法,这个注解支持指定的REST API,而不支持整个应用程序。1
2
3
4
5
6(value = "/products")
(origins = "http://localhost:8080")
public ResponseEntity<Object> getProduct() {
return null;
}
Global CORS Configuration
我们需要通过@Bean注解自动注入CORS 配置类来全局控制应用程序的CORS
代码如下:1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/products").allowedOrigins("http://localhost:8080");
}
};
}
}
现在你可以创建一个SpringBoot web应用程序运行在8080端口,而你的RESTful web service应用程序则运行在9090端口。
评论加载中