My last year's post "Enable CORS support in REST services with Spring 3.1" seems causing some confusion. I decided to create an example to show how to enable CORS with Spring rest api. The CorsFilter is same as before:
Below are 2 endpoints from EmployeeController.java:
The update method adds the header Access-Control-Allow-Origin with "*", but delete method doesn't. Therefore, the update method is enabled with CORS, but delete isn't. If delete endpoint is called, the following error will be shown in Chrome:
"cannot load http://localhost:8080/rest/employee/1. Origin http://127.0.0.1:8080 is not allowed by Access-Control-Allow-Origin."
However, the delete method is still invoked on the server side since the pre-flight request (OPTIONS)
allows DELETE method to be called.
The entire project can be downloaded from github. Following README to test it.
My intention was to disable/enable CORS support in each individual method by setting "Access-Control-Allow-Origin", but it seems not working as expected: Although the browser returns correct info, the method call is still invoked on the server side even Access-Control-Allow-Origin is not set. If you are allowed to enable all endpoints with CORS support, the code can be simplified as below:
The only difference is that addHeader("Access-Control-Allow-Origin") is moved out the if check. And then the update method can be simplified as:
The code can be downloaded from github too.