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.