I am trying to send request from angular frontend to REST controller exposed by Spring backend.
REST controller has @CrossOrigin
annotation.
I am using HttpClient to send requests from angular app.
Request:
const httpOptions = {
headers: new HttpHeaders({
'Authorization': 'Basic ' + basicAuthHeader,
})
};
return this.http.get(this.address + this.addressStorage.loginEndpoint + '/' + playerName, httpOptions);
Result:
Access to XMLHttpRequest at 'xxx' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
The same request sent by Postman gives correct response.
My assumption:
I have checked network tab using chrome dev tools:
Is the problem caused by the fact that OPTIONS request is being sent instead of GET request and CORS is allowing only GET method?
Assuming that my guess is correct then is adding this component to spring boot app going to solve my issue?
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CorsFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) servletResponse;
HttpServletRequest request = (HttpServletRequest) servletRequest;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with, authorization");
if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
filterChain.doFilter(servletRequest, servletResponse);
}
}
Unfortunately I currently can't change backend implementation so I am unable to find it out myself.
Additional info:
registerPlayer(player: PlayerDTO): Observable<Object> {
const httpOptions = {
headers: new HttpHeaders({'Content-Type': 'application/json'}),
};
return this.http.post(this.address + this.addressStorage.createUserEndpoint, player, httpOptions);
}
This request send to the same controller but on different endpoint returns correct responses.