Sep 18, 2015

The Cross-origin Resource Sharing (CORS) Error

If you are here, maybe you haven't found a working solution for the CORS error message yet, but whatever is your scenario or technology/programming language, take a look here and understand how to solve this error.

The CORS error happens when the client tries to access some of the server's resources that has restricted access, like a javascript, image or font file. The CORS is a security mechanism, that blocks any access to its protected resources, from requests/clients that aren't in the same domain, for example, "client.com" do a request for the "server.js" file at "server.com/server.js". The CORS error is a client-side error message, like this:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading
the remote resource at http://client.com/getfromserver. 
(Reason: CORS header 'Access-Control-Allow-Origin' missing).

The error can't be solved on the client side, so you will need add to the CORS filter the missing header, on the server, allowing clients/requests outside of its domain to access the protected resources. Below you can see how to do this using Java and Spring MVC, if you are using any other server technology, the idea is the same, just search for your server technology + CORS filter solution.

Start creating a new class "CORSFilter" with this content:

package com.l3oc;

import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.filter.OncePerRequestFilter;

public class CORSFilter extends OncePerRequestFilter {

 @Override
 protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
  response.addHeader("Access-Control-Allow-Origin", "*");
  
  if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod())) {
   response.addHeader("Access-Control-Allow-Methods", "GET, POST");
                        response.addHeader("Access-Control-Allow-Headers", "Content-Type");
   response.addHeader("Access-Control-Max-Age", "1");
  }
  
  filterChain.doFilter(request, response);
 }

}

And in the "web.xml" add:

<filter>
 <filter-name>cors</filter-name>
 <filter-class>com.l3oc.CORSFilter</filter-class>
</filter>

<filter-mapping>
 <filter-name>cors</filter-name>
 <url-pattern>/*</url-pattern>
</filter-mapping>

That's all, now you should get rid of the CORS error message and be able to access the server's resources!

About the versions
  • Spring MVC 4.0.2
  • Java 1.8

2 comments :

  1. It work well on my side. Thank so much

    ReplyDelete
    Replies
    1. glad to hear that, you are welcome!

      Delete