I have a web application that I am developing using Angular 2 and Spring Boot. I use the spring-boot-data-rest
dependency to expose my repositories as HTTP endpoints.
During development, I run my backend spring boot project on a local tomcat that runs on port 8080. To develop the frontend, I use the angular-cli to serve my Angular 2 application on port 4200. My frontend running on 4200 needs to be able to hit the endpoints exposed on 8080, but that doesn't work because:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.
If these were custom endpoints that I manually typed in a @RestController
, I could simply add the @CrossOrigin
annotation as such:
@RestController
public class MyController {
@CrossOrigin(origins = "http://localhost:4200")
@RequestMapping(value = "/whatever")
public void whatever() {
//whatever
}
}
But I obviously cannot do this for my endpoints exposed by spring-boot-data-rest
. So, how can I make those endpoints accessible from the http://localhost:4200
origin?
I've used my custom CORS filter to make it work:
/**
* Filter for enabling CORS support.
*/
@Component
public class CorsFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(final HttpServletRequest request, final HttpServletResponse response,
final FilterChain filterChain) throws ServletException, IOException {
response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, PATCH, HEAD, OPTIONS");
response.addHeader("Access-Control-Allow-Headers", "Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");
response.addHeader("Access-Control-Expose-Headers", "Access-Control-Allow-Origin, Access-Control-Allow-Credentials");
response.addHeader("Access-Control-Allow-Credentials", "true");
response.addIntHeader("Access-Control-Max-Age", 10);
filterChain.doFilter(request, response);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With