尽管允许所有源、所有方法和所有头,CORS错误并没有得到修复



我们使用了Java Spring引导和React-CRA。我们使用AWS EC2部署了服务器,使用AWS S3部署了客户端。

但由于CORS错误,该网站无法正常工作。

这是我在控制台中看到的错误:

GET http://ec2-13-125-208-244.ap-northeast-2.compute.amazonaws.com:8080/api/questions/1/answers net::ERR_FAILED 200

我们尝试。。。。。

<在客户端>

我们在开发阶段使用了"http代理中间件",并使用.env.development/.env.production环境变量将服务器地址部署到EC2。(在.env.production中放入EC2服务器地址,在.env.development中放入空字符串("(以解决本地问题。(

此外,我们正在使用axios,并尝试在请求标头中放入{withCredentials:true}

在使用环境变量之前,请使用实例设置baseUrl。

const instance = axios.create({baseURL: '``https://http``://~~.s3-website.ap-northeast-2.amazonaws.com/'});

在"localhost:3000"中,它运行良好。但它不能与使用AmazonS3的静态网站配合使用。

<在Sever>

我们像这样编写了与CORS相关的代码,但没有成功。

@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("*"));
configuration.setAllowedMethods(Arrays.asList("GET","POST", "PATCH", "DELETE"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("http://localhost:3000", "http://pre-project-038-client.s3-website.ap-northeast-2.amazonaws.com/questions"));
configuration.setAllowedMethods(Arrays.asList("GET","POST", "PATCH", "DELETE"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}

我知道它很容易受到安全攻击,但我写了以下代码来解决Java中的CORS错误。

@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.addAllowedOrigins(Arrays.asList("*"));
configuration.addAllowedMethods(Arrays.asList("*"));
configuration.addAllowedHeader(Arrays.asList("*"));
configuration.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}

响应状态为200,但由于CORS错误,屏幕上仍然没有加载任何数据。

我们可以在客户端或服务器端尝试什么?

我在应用程序中遇到了同样的问题,我的解决方案是在HttpSecurity中配置它。代码为:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
CorsConfiguration corsConfiguration = new CorsConfiguration().applyPermitDefaultValues();
corsConfiguration.addAllowedMethod("*");
httpSecurity
.authorizeRequests()
.antMatchers("/**").permitAll()
.anyRequest().permitAll()
.and()
.cors().configurationSource(request -> corsConfiguration)
.and()
.csrf().disable();
}
}

最新更新