我托管在http://localhost:4200的Angular Web应用程序发出了一个请求http://localhost:8888/mydomain/path 对于我的Spring Boot Java后端,如下所述:
棱角前端面:
const headers = new HttpHeaders();
headers.set('Content-Type', 'application/json');
headers.set('Access-Control-Allow-Origin', '*');
headers.set('Access-Control-Allow-Methods', 'GET,POST,OPTIONS,DELETE,PUT');
this.http.get('http://localhost:8888/mydomain/path', { headers: headers })
.subscribe(result => console.log(result));
在互联网上搜索,我在Java/Spring Boot后端找到了一个解决CORS来源问题的设置
@EnableWebSecurity
@Configuration
public class SecurityConfigurations extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers(HttpMethod.GET, "/*").permitAll()
.antMatchers(HttpMethod.POST, "/*").permitAll()
.antMatchers(HttpMethod.PUT, "/*").permitAll()
.antMatchers(HttpMethod.DELETE, "/*").permitAll()
.and().csrf().disable().cors().disable();
}
@Bean
@Qualifier("corsFilter")
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("http://localhost:4200");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
}
但是GET调用返回了下面的错误.会有什么问题呢?我忘了做什么或做错了什么??非常感谢
'http://localhost:8888/mydomain/path' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.