【问题标题】:CORS blocked - Spring Boot and ReactCORS 受阻 - Spring Boot 和 React
【发布时间】:2021-07-03 17:36:27
【问题描述】:

我有我的 Spring Boot REST API。链接:“http://localhost:8080/api/components/component/list”

对于前端,我使用的是 React,上面是我希望 React Admin 应用使用的链接。

这是我的 Spring Boot 的 CORS 代码,它位于一个名为 CorsConfig 的单独类中:

@Configuration
public class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry myCorsRegistry){
             myCorsRegistry.addMapping("/**")
            .allowedOrigins("http://localhost:3000")  //frontend's link
            .allowedHeaders("*")
            .allowedMethods("*")
            .allowCredentials(true)
            .maxAge(4800);
     }

}

我也试过了,还是不行:

@Configuration
public class CorsConfig{

   @Bean
   public WebMvcConfigurer corsConfigurer() {
       return new WebMvcConfigurerAdapter() {
           @Override
           public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/api/**")
                    .allowedOrigins("http://domain2.com")
                    .allowedMethods("PUT", "DELETE")
                    .allowedHeaders("header1", "header2", "header3")
                    .exposedHeaders("header1", "header2")
                    .allowCredentials(false).maxAge(3600);
           }
       };
    }
}

对于我的控制器类,我有以下内容:

@CrossOrigin
@RequestMapping("/api/components/component")
@RestController
public class Component{
     @Autowired
     //code...
}

这是我的反应代码:

const parentURL = 
restProvider(`http://localhost:8080/api/components/component`);

function App() {
    return(
       <Admin dataProvider={parentURL}>
          <Resource name="list" list={ListGuesser} />
        </Admin>
    );
 }

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

Access to fetch at 'http://localhost:8080/api/components/component/DashBoard? 
filter=%7B%7D&range=%5B0%2C9%5D&sort=%5B%22id%22%2C%22ASC%22%5D' from origin 'http://localhost:3000' 
has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 
'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response 
serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

我的问题: 如何解决上述错误?

【问题讨论】:

  • 试试allowedOrigins("*"),如果可行请告诉我
  • 在控制器中添加@CrossOrigin 注释时,尝试在那里指定原点。它应该工作。 @CrossOrigin(origins = "*")
  • sai manoj:您是在内置 tomcat 服务器中运行 sprint 启动应用程序,还是在 tomcat 或任何其他服务器中部署 jar 或 war 文件?

标签: javascript java reactjs spring spring-boot


【解决方案1】:

请在您的项目中添加以下文件,该文件位于主 spring boot 类所在的包中。这对我在 Spring boot 和 React 生态系统中的所有 CORS 问题都有效。

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
@EnableWebMvc
public class CorsWebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**");
        registry.addMapping("/*.html");
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addRedirectViewController("/api/v2/api-docs", "/v2/api-docs");
        registry.addRedirectViewController("/api/swagger-resources/configuration/ui",
                "/swagger-resources/configuration/ui");
        registry.addRedirectViewController("/api/swagger-resources/configuration/security",
                "/swagger-resources/configuration/security");
        registry.addRedirectViewController("/api/swagger-resources", "/swagger-resources");
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/swagger-ui.html**")
                .addResourceLocations("classpath:/META-INF/resources/swagger-ui.html");
        registry.addResourceHandler("/api/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }}

【讨论】:

    【解决方案2】:

    尝试在控制器顶部添加 @CrossOrigin(origins ="http://localhost:3000")。它应该可以工作。

    【讨论】:

      【解决方案3】:

      哦,是的,这个 CORS 的实现非常糟糕。我被 React + Spring Boot + Spring Security 困住了。

      帮助我的是

      @Configuration
      public class CorsConfig{
      
         @Bean
         public WebMvcConfigurer corsConfigurer() {
             return new WebMvcConfigurerAdapter() {
                 @Override
                 public void addCorsMappings(CorsRegistry registry) {
                      registry.addMapping("/api/**")
                          .allowedOrigins("http://domain2.com")
                          .allowedMethods("*");
                 }
             };
          }
      }
      

      我建议您多尝试一下这种方法。我可以肯定的是,您在allowedMethods 中输入的内容很重要。我完全记得,当我列出所有可能的方法(包括选项)时,它对我不起作用。但只要我把它改成"*",它就起作用了。

      我还在我的 configure Spring Security 方法的末尾有单独的 http.cors();,以防有人想知道这个特殊情况。

      【讨论】:

        猜你喜欢
        • 2021-06-20
        • 2020-05-03
        • 2020-07-05
        • 2021-07-03
        • 2021-01-23
        • 2021-08-17
        • 2016-05-04
        相关资源
        最近更新 更多