简体   繁体   中英

Spring Boot + React CORS issue without spring security

I'm using Spring Boot 2.2.2.RELEASE as a REST service and React for front-end.

Just a simple GET method implemented, But getting CORS issue when communicating to the server via REACT.

https://spring.io/guides/gs/rest-service-cors/ -> followed this link, but no luck.

my Spring Boot Controller:

@RestController
public class FeedController {
    @Autowired
    private IFeedService IFeedService;

    @CrossOrigin(origins = "http://localhost:3000")
    @GetMapping(path="/v1/getdashboard")
    public ResponseEntity<String> feedDashBoardController(){
        String result = null;
        HttpStatus httpStatus = HttpStatus.BAD_REQUEST;
        try {

             List<FeedData> dashBoardFeedInfo = IFeedService.getDashBoardFeedService();

             // Create ObjectMapper
            ObjectMapper mapper = new ObjectMapper();
            JsonNode dataNode = mapper.valueToTree(dashBoardFeedInfo);

            result = FeedResponseData.generateFeedResponse(dataNode);
            httpStatus = HttpStatus.OK;

        }catch(TBServiceException e) {
            result = AppExceptions.handleException("Something Went Wrong");
            httpStatus = HttpStatus.BAD_REQUEST;
        }

        return new ResponseEntity<String>(result,httpStatus);
    }
}

my Spring Boot Application:

@SpringBootApplication
public class TechnicalBlogApplication {

    public static void main(String[] args) {
        SpringApplication.run(TechnicalBlogApplication.class, args);
        System.out.println("Application Main - Update -1");

    }

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/v1/getdashboard").allowedOrigins("http://localhost:3000");
            }
        };
    }
}

my Spring application properties:

spring.profiles.active=dev
server.port=6001
server.servlet.context-path=/technical-blog

my React Code Snippet:

async componentDidMount() {
const dashboardData= await fetch("http://localhost:6001/technical-blog/v1/getdashboard");

console.log("dash ",dashboardData)
}

I have also tried setting the headers, below is the re-modified controller. i got multi CORS definition error.

@RestController
public class FeedController {
@Autowired
private IFeedService IFeedService;

@CrossOrigin(origins = "http://localhost:3000")
@GetMapping(path="/v1/getdashboard")
public ResponseEntity<String> feedDashBoardController(){
    String result = null;
    HttpStatus httpStatus = HttpStatus.BAD_REQUEST;
    try {

         List<FeedData> dashBoardFeedInfo = IFeedService.getDashBoardFeedService();

         // Create ObjectMapper
        ObjectMapper mapper = new ObjectMapper();
        JsonNode dataNode = mapper.valueToTree(dashBoardFeedInfo);

        result = FeedResponseData.generateFeedResponse(dataNode);
        httpStatus = HttpStatus.OK;

    }catch(TBServiceException e) {
        result = AppExceptions.handleException("Something Went Wrong");
        httpStatus = HttpStatus.BAD_REQUEST;
    }

    return new ResponseEntity<String>(result,setHeaders(),httpStatus);
}
}

private HttpHeaders setHeaders() {
    List<HttpMethod> allowedMethods = new ArrayList<>();
    allowedMethods.add(HttpMethod.GET);
    allowedMethods.add(HttpMethod.POST);

    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setContentType(MediaType.APPLICATION_JSON);
    //httpHeaders.setAccessControlAllowOrigin("*");
    httpHeaders.setAccessControlAllowCredentials(true);
    httpHeaders.setAccessControlAllowMethods(allowedMethods);
    httpHeaders.setAccessControlMaxAge(3600);
    return httpHeaders;
}

i think you should put @CrossOrigin(origins = "http://localhost:3000") on the controller it self because the first thing that request goes to is the controller not the function

so it will be like that

@RestController
@CrossOrigin(origins = "http://localhost:3000")
public class FeedController {
@Autowired
private IFeedService IFeedService;


@GetMapping(path="/v1/getdashboard")
public ResponseEntity<String> feedDashBoardController(){
    String result = null;
    HttpStatus httpStatus = HttpStatus.BAD_REQUEST;
    try {

         List<FeedData> dashBoardFeedInfo = IFeedService.getDashBoardFeedService();

         // Create ObjectMapper
        ObjectMapper mapper = new ObjectMapper();
        JsonNode dataNode = mapper.valueToTree(dashBoardFeedInfo);

        result = FeedResponseData.generateFeedResponse(dataNode);
        httpStatus = HttpStatus.OK;

    }catch(TBServiceException e) {
        result = AppExceptions.handleException("Something Went Wrong");
        httpStatus = HttpStatus.BAD_REQUEST;
    }

    return new ResponseEntity<String>(result,setHeaders(),httpStatus);
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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