Home > Software design >  CORS issue when running Spring Boot with Angular using @CrossOrigin at controller level
CORS issue when running Spring Boot with Angular using @CrossOrigin at controller level

Time:06-09

I'm getting a CORS error when running calls to the Spring Boot 2.6.4 web service

enter image description here

Here is the code in Angular 13:

let headers = new HttpHeaders({
  'Content-Type': 'application/json',
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Headers': 'Content-Type',
  'Access-Control-Allow-Methods': 'GET,POST,OPTIONS,DELETE,PUT'
});
let options = { headers: headers };

this.http.get<any>("http://localhost:8080/country/available", options).subscribe(data => {
  console.log(data);
});

I have the controller annotated with @CrossOrigin at the controller level:

@RestController
@CrossOrigin(origins = "*", maxAge = 3600)
@RequestMapping("country")
public final class CountryController {

    private final transient CountryService countryService;

    @Autowired
    public CountryController(final CountryService countryService) {
        this.countryService = countryService;
    }


    @GetMapping("/available")
    public List<Country> getAvailableCountries() {
        return countryService.getAvailableCountries();
    }
}

CodePudding user response:

 'Access-Control-Allow-Origin': '*',
 'Access-Control-Allow-Headers': 'Content-Type',
 'Access-Control-Allow-Methods': 'GET,POST,OPTIONS,DELETE,PUT'

Remove this 3 headers from your angular HTTP call. This are response headers and specified by BE not by FE.

CodePudding user response:

Try this @CrossOrigin(origins = "*", allowedHeaders = "*" ,maxAge = 3600)

or you can do it in the security configuration as http.cros()

  • Related