2

There is a React frontend app which is running on localhost:3000 and java backend app which is running on localhost:8080

All GET endpoints are working fine but if I try to send a POST request then I'm getting cors error:

Access to fetch at 'http://localhost:8080/api/cars' from origin 'http://localhost:3000'
has been blocked by CORS policy: Response to preflight request doesn't pass access 
control check: The value of the 'Access-Control-Allow-Credentials' header in the response
is '' which must be 'true' when the request's credentials mode is 'include'.

If I test the same POST endpoint in Postman everything also works fine

call from react app:

export async function addCar(body) {

    const response = await post(`http://localhost:8080/api/cars`, body)

    return response;
}


export async function post(url, body) {

  const response = await fetch(url, {
      method: "POST",
      mode: "cors",
      credentials: "include",
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(body),
    });

  return response;
}

here is my backend implementation. I tried to configure WebConfig but it didn't help

@Slf4j
@RestController
@RequestMapping("/api/cars")
@RequiredArgsConstructor(onConstructor = @__({@Autowired}))
@CrossOrigin(origins = "http://localhost:3000")
public class CarController {

    private final CarService carService;

    @RequestMapping(method = POST, produces = APPLICATION_JSON_VALUE, consumes = APPLICATION_JSON_VALUE)
    public ResponseEntity<?> insertCar(@RequestBody @Valid CarDto car) {
        return carService.addCar(car);
    }
}

@Configuration
@EnableCaching
@ConfigurationPropertiesScan
@RequiredArgsConstructor
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/**")
                .allowedOrigins("http://localhost:3000")
                .allowedMethods("*");
    }

}

I would appreciate if someone can help me to fix this issue.

LDropl
  • 846
  • 3
  • 9
  • 25

1 Answers1

0

Please, consider adding to your CorsRegistry all methods that you wanna be available via CorsRegistation#allowedMethod(String ...).

e.g.

        registry.addMapping("/**")
            .allowedOrigins("*") // Specifica l'origine consentita
            .allowedMethods("GET", "POST", "PUT", "DELETE") // Specifica i  metodi consentiti
            .allowedHeaders("*") // Specifica gli headers consentiti
            .allowCredentials(false).maxAge(3600);

Also, the error tells you a lots of stuff:

The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'

Now, I have never developed front-end, since I am a back-ender, but you oughta set as 'true' the header property 'Access-Control-Allow-Credentials'. I guess it is:

export async function post(url, body) {

    const response = await fetch(url, {
        method: "POST",
        mode: "cors",
        credentials: "include",
        headers: {
           'Accept': 'application/json',
           'Content-Type': 'application/json'
           'Access-Control-Allow-Credentials': 'true'
        },
        body: JSON.stringify(body),
    });

    return response;
 }
DynoZ
  • 169
  • 1
  • 8