Skip to content
Advertisement

Empty response after aplying CORS policy Springboot

When I don’t touch anything about CORS, the browser shows me the common error

Access to fetch at ‘http://localhost:8080/denodo-testwebapp/tags’ from origin ‘http://localhost:3000’ has been blocked by CORS policy

But meanwhile doing a GET petition on postman I recive the response with all the data

  GET http://localhost:8080/test-webapp/tags/

Response: [
    {
        "name": "Tag1"
    },
    {
        "name": "Tag12"
    },
    {
        "name": "Tag123"
    }
]

But when I try to disable CORS by adding this code:

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class MyConfiguration implements Filter {

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) {

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        response.setHeader("Access-control-Allow-Origin", "http://localhost:3000");
        response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, HEAD,OPTIONS, DELETE");
        response.setHeader("Access-Control-Allow-Headers", "Accept, Accept-Language, Authorization, Cache-Control, Content-Language, Content-Type, X-Requested-With");
        response.setHeader("Access-Control-Exposed-Headers", "Accept-Ranges, Access-Control-Allow-Credentials, Access-Control-Allow-Origin, Cache-Control, Content-Language, Content-Length, Content-Type, Date, ETag, Expires, Last-Modified, Location, Pragma, Server, Transfer-Encoding, Vary, WWW-Authenticate");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Credentials", "true");

    }

    public void init(FilterConfig filterConfig) {
    }

    public void destroy() {
    }

}

I no longer have the browser error, but now, making the same GET petition on postman the response is empty and I don’t exactly know what is interfiering here

Advertisement

Answer

You need to forward the request/response pair down the FilterChain by calling chain.doFilter(request, response); at the end of your method.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement