【发布时间】:2023-01-02 18:33:07
【问题描述】:
我们使用了 Java-Spring boot 和 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-proxy-middleware',并使用.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/'});
在“本地主机:3000”中,它工作正常。但它不适用于使用 Amazon S3 的静态网站。
<在服务器>
我们这样写了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 错误,屏幕上仍未加载任何数据。
我们可以在客户端或服务器端尝试什么?
【问题讨论】:
-
从控制台查看错误消息。您是否尝试过在不包含凭据的情况下从客户端发出相同的请求?
标签: java spring-boot cors access-control-allow-origin