D
D
dissdoc2016-06-14 12:04:10
Nginx
dissdoc, 2016-06-14 12:04:10

How to fix redirect error (CORS)?

There is a bunch of Angular (frontend) + Nginx (proxy) + Spring (backend)
And there is one condition under which the filter works on the backend

public class MyFilter implements Filter {
    //...
       HttpServlerResponse response = (HttpServletResponse) servletResponse;
       response.sendRedirect("http://yandex.ru");
    //...
}

On angular just $http.get("/rest/auth")
As a result I get the following error
XMLHttpRequest cannot load localhost:9595/auth. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ' localhost:7776 ' is therefore not allowed access.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Kosarev, 2016-06-14
@jaxtr

Add a filter like this:

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

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        httpServletResponse.setHeader("Access-Control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Max-Age", "3600");
        if (!"OPTIONS".equalsIgnoreCase(httpServletRequest.getMethod())) {
            chain.doFilter(request, response);
        }
    }

    @Override
    public void init(FilterConfig filterConfig) {
    }

    @Override
    public void destroy() {
    }
}

In a good way, you still need to determine whether the specified Origin has permission to use it. Plus, you will also need the Access-Control-Allow-Methods headers (a comma-separated list of allowed methods for CORS) and Access-Control-Allow-Headers (a comma-separated list of allowed CORS headers).
If you do this within a normal web application, then the @Component and @Order(Ordered.HIGHEST_PRECEDENCE) annotations can be removed, and the filter itself can be written in web.xml.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question