Spring Boot + React CORS проблема без весенней безопасности - PullRequest
0 голосов
/ 25 апреля 2020

Я использую Spring Boot 2.2.2.RELEASE в качестве службы REST и React для внешнего интерфейса.

Просто реализован простой метод GET, но возникает проблема с CORS при взаимодействии с сервером через REACT.

https://spring.io/guides/gs/rest-service-cors/ -> перешел по этой ссылке, но не повезло.

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

свойства моего приложения Spring:

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

мой фрагмент кода реакции:

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

console.log("dash ",dashboardData)
}

Я также попытался установить заголовки, ниже приведен модифицированный контроллер. я получил ошибку определения нескольких CORS.

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

1 Ответ

0 голосов
/ 25 апреля 2020

я думаю, вы должны поставить @CrossOrigin(origins = "http://localhost:3000") на контроллер сам, потому что первое, на что идет запрос, это контроллер, а не функция

, поэтому он будет выглядеть так

@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);
}
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...