简体   繁体   English

在开发Spring Boot和reactjs应用程序期间处理CORS

[英]Handling CORS during development Spring Boot and reactjs application

this problem is kinda new to me because I used to develop angular applications earlier but now I have reactjs as a front-end technology. 这个问题对我来说是一个新问题,因为我以前曾经开发过角度应用程序,但是现在我已经将reactjs作为前端技术。

My problem is CORS. 我的问题是CORS。 My react app works on port 3000 and my spring boot app on 8080. Adding @CrossOrigin on my controller handles the problem pretty well but is there a way to somehow configure this on the front-end side? 我的react应用程序可以在端口3000上运行,而我的spring boot应用程序可以在8080上运行。在控制器上添加@CrossOrigin可以很好地解决此问题,但是是否可以通过某种方式在前端进行配置? Something like a switch that you flip when app is supposed to work locally and stop this when working in production environment? 像是某个开关,当应用程序在本地运行时会翻转,而在生产环境中运行时会停止该开关吗?

Yes. 是。 You can use reverse proxy. 您可以使用反向代理。

It's very common problem. 这是很常见的问题。

See here. 看这里。

http://www.pierre-beitz.eu/2017/01/24/Dealing-with-CORS-in-a-Development-Environment-Using-a-Reverse-Proxy.html http://www.pierre-beitz.eu/2017/01/24/Dealing-with-CORS-in-a-Development-Environment-Using-a-Reverse-Proxy.html

By that all requests would be going to api and will further resolve issue. 这样,所有请求都将发送到api,并将进一步解决问题。

Right now on phone. 现在在电话上。 Can come on lappy if you have any more questions. 如果您还有其他问题,可以随便吃。

Adding another solution post comment 添加其他解决方案评论

Add the following code in your MainApplication.java 在MainApplication.java中添加以下代码

@Bean
    public FilterRegistrationBean corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("http://domain1.com");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        bean.setOrder(0);
        return bean;
    }

and map the class with @Configuration annotation 并使用@Configuration注释映射类

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM