我正在使用jhipster V4.5.6开发一个spring boot应用程序。但无法配置CORS。
这是我的application-dev.yml文件:
# CORS is only enabled by default with the "dev" profile, so BrowserSync can access the API
cors:
allowed-origins: "http://localhost:9000"
allowed-methods: GET, PUT, POST, DELETE, OPTIONS
allowed-headers: "*"
exposed-headers:
allow-credentials: true
max-age: 1800
WebConfigurer.java如下:
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = jHipsterProperties.getCors();
if (config.getAllowedOrigins() != null && !config.getAllowedOrigins().isEmpty()) {
log.debug("Registering CORS filter");
source.registerCorsConfiguration("/api/**", config);
source.registerCorsConfiguration("/v2/api-docs", config);
}
return new CorsFilter(source);
}
SecurityConfiguration.java文件如下:
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring()
.antMatchers(HttpMethod.OPTIONS, "/**")
.antMatchers("/test/**");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf()
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.and()
.addFilterBefore(corsFilter, UsernamePasswordAuthenticationFilter.class)
.exceptionHandling()
.authenticationEntryPoint(http401UnauthorizedEntryPoint())
.and()
.authorizeRequests()
... //Some project specific configuration
}
现在,我可以使用GET请求了。但是当我使用POST时如下:
private demoCors(restUrl: string, input: any): Observable<Result> {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.post(restUrl, JSON.stringify(input), options)
.map(this.extractData)
.catch(this.handleError);
}
我收到以下错误:
POST http://localhost:8080/api/dth 403 (Forbidden)
XMLHttpRequest无法加载 http://localhost:8080/api/dth。没有 请求中存在“Access-Control-Allow-Origin”标头 资源。因此不允许来源“http://localhost:9000” 访问。响应的HTTP状态代码为403。
有人可以建议如何解决它吗?
答案 0 :(得分:-1)
你能试试吗?
# CORS is only enabled by default with the "dev" profile, so BrowserSync can access the API
cors:
allowed-origins: "*"
allowed-methods: GET, PUT, POST, DELETE, OPTIONS
allowed-headers: "*"
exposed-headers:
allow-credentials: true
max-age: 1800