No 'Access-Control-Allow-Origin' header is present on the requested resource | Firebase Cloud Firestore - Java - Ionic

156 views Asked by At

I'm developing an application and I'm using Ionic (Angular) for client side, java (JAX-RS) as backend and Firebase Cloud Firestore for persistence. Maybe this stack is weird but I'm new in create real applications and Firebase caughy my attention.

I want to save data in Firebase Cloud Firestore using Ionic with an REST API, I can do this with tools like postman, but i can't with Ionic, I'm getting an error No 'Access-Control-Allow-Origin' header is present on the requested resource. You will say to me that configure my server to allow requests but I do this already, I test my REST API without including the part of saving data in Firebase Cloud Firestore, and this work perfectly, I don't get that error. The problem only spends when I call a Firebase method.

Server Configuration

I add the following Java Class

package api;

public class RestCorsFilter implements Filter {

    @Override
    public void destroy() {
        //enter code here
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        HttpServletResponse resp = (HttpServletResponse) response;
        resp.addHeader("Access-Control-Allow-Origin", "*");
        resp.addHeader("Access-Control-Allow-Headers", "*");
        resp.addHeader("Access-Control-Allow-Methods", "*");

        chain.doFilter(request, resp);

    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {

    }

}

And then, I add this fragment in web.xml

<filter>
    <filter-name>RestCorsFilter</filter-name>
    <filter-class>api.RestCorsFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>RestCorsFilter</filter-name>
    <url-pattern>/api/*</url-pattern>
</filter-mapping>

My application path:

@ApplicationPath("/api")
1

There are 1 answers

1
David Riscanevo On

I was facing this error because every exception caused in the java application was showed in browser's console as a CORS error. The solution was look at the application log to catch and deal with the exception generated by the application.