Home > Net >  blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present, but it literal
blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present, but it literal

Time:08-06

ok i'm quite sure you guys know this error so let's just skip on my solution and the reasons of it not working, I have an Interceptor which is basically a filter, where I did this:

@Component
public class AllRequestInterceptor implements HandlerInterceptor {
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        
        if(request.getMethod().equalsIgnoreCase("options")) {
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "*");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Headers", "*");
        }
        
        for(String header: response.getHeaderNames()) {
            System.out.println(header);
        }
        
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }
}

the CORS preflight request actually enters the if block, I get the headers printed afterwards and they're all present, and yet that party-pooper says otherwise, why does it say otherwise?

CodePudding user response:

I'm not sure if this is what you are looking for, but this worked for me.

@Configuration
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CorsInterceptor implements Filter{

    public CorsInterceptor() {
    }



    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest request = (HttpServletRequest) req;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "*");

        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            chain.doFilter(req, res);
        }
    }

    @Override
    public void init(FilterConfig filterConfig) {
    }

    @Override
    public void destroy() {
    }
}

CodePudding user response:

CORS must be sent on all requests, not just on OPTIONS: CORS HEADERS present only on preflight or every request

Simply remove if(request.getMethod().equalsIgnoreCase("options")) and its corresponding brackets, and it should work.

  • Related