I have an interceptor:
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new RequestInterceptor());
}
Can I add my CORS configuration in the RequestInterceptor.java above? Like this:
public class RequestInterceptor extends HandlerInterceptorAdapter
{
...
public boolean preHandle(
HttpServletRequest request,
HttpServletResponse response,
Object handler) throws Exception {
...
...
if (request.getMethod().equals("OPTIONS")) {
response.setHeader("Access-Control-Allow-Origin", "http://localhost:9090");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
response.setHeader("Access-Control-Expose-Headers", "*");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Max-Age", "4800");
}
...
return true;
}
}
I do not want any of these methods because for some reason they are not working for me:
@CrossOrigin
OR
WebMvcConfigurerAdapter -> addCorsMapping()
The only thing works for me is having a CORSFilter and mapping it in the web.xml. But that got me thinking that Interceptors are also kind of Filter, aren't they? Then why to add a Filter AND an interceptor when interceptor itself will do.
Anyway, I tried with the above piece of code and my requests are landing in the server and the rest controller method is running, but I see this response on my ReactJs page:
SEC7120: Origin http://localhost:9090 not found in Access-Control-Allow-Origin header.
SCRIPT7002: XMLHttpRequest: Network Error 0x80070005, Access is denied.
What am I missing? Is there anything else I have to do in the RequestInterceptor.java class for CORS?
Thanks.
User contributions licensed under CC BY-SA 3.0