Reputation: 6140
I have the following class
@RestController
@RequestMapping("/bets")
@CrossOrigin
public class BetRestController {
@Autowired
private BetController betController;
@ResponseBody
@RequestMapping(method=RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public BetResource betOnGame(@RequestBody @Valid BetResource betResource) {
return BetTranslator.from(betController.betOnGame(BetTranslator.from(betResource)));
}
@ResponseBody
@RequestMapping(method = RequestMethod.GET)
public List<BetResource> getAllBets() {
return betController.getAllBets().stream().map(BetTranslator::from).collect(Collectors.toList());
}
}
The problem is that when I try to access the POST method I am getting:
XMLHttpRequest cannot load http://localhost:8080/bets. Origin http://localhost:3000 is not allowed by Access-Control-Allow-Origin.
but GET method works.
What I have wrong in my configuration or maybe there is a bug in @CrossOrigin annotation processing?!
Upvotes: 1
Views: 3220
Reputation: 4558
If I understand your problem correctly, it is possible to specify CORS origin on one specific method.
Sprint Boot documentation : https://spring.io/guides/gs/rest-service-cors/
Enabling CORS
Controller method CORS configuration
So that the RESTful web service will include CORS access control headers in its response, you just have to add a @CrossOrigin annotation to the handler method:
Here's the example from Spring boot website :
@CrossOrigin(origins = "http://localhost:9000")
@RequestMapping("/greeting")
public @ResponseBody Greeting greeting(@RequestParam(required=false, defaultValue="World") String name) {
System.out.println("==== in greeting ====");
return new Greeting(counter.incrementAndGet(), String.format(template, name));
}
Upvotes: 2