在已部署的 reactjs + springboot 应用程序上启用 CORS 请求

Enable CORS request on deployed reactjs + springboot application

我有全栈应用程序,前端有 reactjs,后端有 springboot。在本地主机上运行完美,但是当我将它部署在 google 计算引擎虚拟机上时,它停止工作并开始抛出 CORS 错误。
代码:
反应:

class RegisterPage extends Component {
    constructor(props) {
....
    axios.defaults.headers.post['Content-Type'] = 'application/json;charset=utf-8';
    axios.defaults.headers.post['Access-Control-Allow-Origin'] = '*';
}
....
handleRegister(event) {
...
axios.post('http://localhost:8443/api/v1/auth/sign-up', credentials)
            .then((response) => {
                this.setState({
                    requestResult: "registration successful!"
                })
            }).catch(resp => {
            this.setState({
                requestResult: "something went wrong :("
            })
        })
...
}

我还添加了映射到 Spring:

@SpringBootApplication
public class PoisApplication {
    public static void main(String[] args) {
        SpringApplication.run(PoisApplication.class, args);
    }
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "HEAD");
            }
        };
    }
}

可能是什么问题?我现在没有想法,所以任何帮助都会很棒。

编辑:尝试将此添加到 spring 安全性

protected void configure(HttpSecurity http) throws Exception {
        http.cors().and(). ...
...
}

@Bean
    CorsConfigurationSource corsConfigurationSource() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
        return source;
    }

甚至这个

@Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("http://localhost:3000",
"http://my_ip:3000"));
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "HEAD", "OPTIONS"));
        configuration.setAllowedHeaders(Arrays.asList("Access-Control-Allow-Headers", "Access-Control-Allow-Origin",
                "Access-Control-Request-Method", "Access-Control-Request-Headers", "Origin",
                "Cache-Control", "Content-Type"));
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

没有任何帮助!

所以,问题和我想的不一样。浏览器控制台中的 CORS 错误可能意味着 'no response from server',这就是问题所在 - 我的 React 前端正在向错误地址发出请求(部署在 google 计算引擎上的 React 服务器正在向 localhost 发出请求 - 并且以某种方式向 localhosts表示我的计算机,我正在使用的计算机,显然,我没有在我的本地主机上启动 spring 服务器)。 如果有人遇到此问题,请检查您期望响应的域。