Home > Software engineering >  Access to XMLHttpRequest has been blocked by CORS policy eventhough Controller has Crossorigin enabl
Access to XMLHttpRequest has been blocked by CORS policy eventhough Controller has Crossorigin enabl

Time:01-04

I am trying to post data to a MariaDB, by passing it through my service into the controller and then into the repository. However, when trying to make a http.post to the controller URL, I get the response: Access to XMLHttpRequest at 'http://localhost:8080/api/car/create' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. While I've found this error has been described alot of times, the proposed solutions seems to have not worked for me yet, as I both enabled everything in the http-header aswell as enable @Crossorigin in my controller.

Here are the important parts of my code:

Service

  readonly httpOptions = {
    headers: new HttpHeaders({
      "ACCESS_CONTROL_ALLOW_ORIGIN": "http://localhost:4200",
      "ACCESS_CONTROL_ALLOW_CREDENTIALS": "true"
    })
  };

  public save(car: Car) {
    return this.http.post('http://localhost:8080/api/car/create', car, this.httpOptions);
  }

Controller

@Controller
@RequestMapping("/api/car")
@CrossOrigin(origins = "http://localhost:4200")
@Transactional
public class CarController {

    @Autowired
    public CarController(CarRepository carRepository) {

        this.carRepository = carRepository;
    }

    @PostMapping(value = "/create")
    @ResponseBody
    @Transactional
    public void addCars(@RequestBody final car car) {
        this.carRepository.save(car);
    }
}

CodePudding user response:

So I'm not sure if that's an optimal solution, but it is a solution.

I added this slice of code, to basically tell the CORS-Config directly to allow CrossOrigin and it seems to have worked:

@Bean
    public WebMvcConfigurer corsConfigurer() {
        System.out.println("CORS Config success");
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**").allowedOrigins("http://localhost:4200"); // "/create-cars"
            }
        };

    }
  • Related