CORS问题与Spring Boot [英] CORS issue with Spring Boot
问题描述
我有一个Spring Boot应用程序运行在端口8443上,一个基于angular2的前端在端口8080上。我需要我的前端向我的Spring服务器发出请求,但是我得到CORS错误左右。我添加了 @CrossOrigin
注释到我的RestController方法,我已经添加了一个CORSFilter到我的项目,并映射到 web.xml
,但在Firefox 46.0a2我仍然在控制台上得到这个错误:
I have a Spring Boot application running on port 8443, and an angular2 based front end on port 8080. I need my front end to make requests to my Spring server, but I'm getting CORS errors left and right. I have added the @CrossOrigin
annotation to my RestController method, and I have added a CORSFilter to my project, and mapped it on web.xml
, but on Firefox 46.0a2 I still get this error on the console:
跨原始请求被阻止: Origin Policy不允许在 https:// localhost:8443 / allEquips 上阅读远程资源
。 (原因:CORS
标题'Access-Control-Allow-Origin'缺失)。
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://localhost:8443/allEquips. (Reason: CORS header 'Access-Control-Allow-Origin' missing).
我的控制器的相关部分:
The relevant part of my controller:
@CrossOrigin
@RequestMapping("/allequips")
List<String> allequips(Model model) {
List<String> codes = equipmentRepository.findAllEquipments();
return codes;
}
CORSFilter:
The CORSFilter:
public class CORSFilter implements Filter{
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
chain.doFilter(req, res);
}
public void init(FilterConfig filterConfig) {}
public void destroy() {}
}
web.xml上的映射
:
<filter>
<filter-name>cors</filter-name>
<filter-class>config.CORSFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>cors</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
我不知道这是否重要,但是使用http请求的Angular2代码:
And I don't know if this is important, but the Angular2 code that's making the http request:
@Injectable()
export class EquipService {
equips: Array<Equip>;
constructor(public http: Http) {
console.log('Equip service created.', http);
}
getEquips() {
return this.http.get(WebServiceEndPoint+'allEquips')
.map((responseData) => {
return responseData.json();
}).map((equips: Array<any>) => {
let result: Array<Equip> = [];
if(equips) {
equips.forEach((equip) => {
result.push(new Equip(equip.code));
});
}
return result;
}).subscribe( res => this.equips = res);
}
}
我缺少某些配置?
编辑:我放弃了并从先前的提交重新启动。之后,只需添加 @ Cross-Origin
就足够了。
I gave up and restarted from a previous commit. After that, simply adding @Cross-Origin
was enough.
推荐答案
第一种方法:
如果您正在使用spring boot,请创建一个新类,扩展webmvcconfigurereAdapter
First Approach:- If you are using spring boot then create a new class that extends webmvcconfigurereAdapter
@Configuration
@ComponentScan
@EnableWebMvc
public class ApplicationConfig extends WebMvcConfigurerAdapter {
@Override
- public void addCorsMappings(CorsRegistry registry) {
- registry.addMapping("/**").allowedMethods("PUT", "GET", "DELETE", "OPTIONS", "PATCH", "POST");
- }
}
第二种方法:
也可以在@springBootApplication类中添加。不需要xml。
Second Approach:- Also you can add this in the @springBootApplication class. No xml needed.
@Bean
public CorsFilter corsFilter() {
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
final CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("OPTIONS");
config.addAllowedMethod("HEAD");
config.addAllowedMethod("GET");
config.addAllowedMethod("PUT");
config.addAllowedMethod("POST");
config.addAllowedMethod("DELETE");
config.addAllowedMethod("PATCH");
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
这篇关于CORS问题与Spring Boot的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!