-1

This is code on Spring Boot side:

class FruitWrapper{

    List<String> fruits;
  }
class HelloController {
    @PostMapping("/")
    public String hello(@RequestBody FruitWrapper fruits)
     {
        System.out.println(fruits);
    
       return "he";
     }

    }

I am sending request from react like this:

 axios.post(`${COURSE_API_URL}`,{"fruits":["apple","orange"]})
.then(resp{console.log(resp.data)})

Error:

 Access to XMLHttpRequest at 'http://localhost:8081/' from origin 'http://localhost:3000'         has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
halfer
  • 19,824
  • 17
  • 99
  • 186
  • check this out; https://stackoverflow.com/questions/46522749/how-to-solve-redirect-has-been-blocked-by-cors-policy-no-access-control-allow – Habil Aug 05 '20 at 06:02

1 Answers1

0

Its happening due to CORS origin policy. You need to enable CORS in your server side. To set the origins for RESTful web service by using @CrossOrigin annotation for the controller method. This @CrossOrigin annotation supports specific REST API, and not for the entire application.

@RequestMapping(value = "/products")
@CrossOrigin(origins = "http://localhost:8080")

public ResponseEntity<Object> getProduct() {
   return null;
}

Global CORS Configuration

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

source: https://www.tutorialspoint.com/spring_boot/spring_boot_cors_support.htm

Zayn
  • 741
  • 1
  • 5
  • 22