首页 > 解决方案 > CORS blocked - Spring Boot and React

问题描述

I have my Spring Boot REST API. Link: "http://localhost:8080/api/components/component/list"

For the frontend, I am using React, above is the link that I want the React Admin app to consume.

Here is my Spring Boot's CORS Code, it is in a separate class called 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);
     }

}

I also tried this, but it still does not work:

@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);
           }
       };
    }
}

For my controller class I have the following:

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

Here is my React Code:

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

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

Here is the error I am getting in my Chrome console:

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.

My Question: How to fix the above error ?

标签: javascriptjavareactjsspringspring-boot

解决方案


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


推荐阅读