5

I used this header method in my servlet doPost method for enable CORS. Though I get CORS error in my reactjs application at the time of fetching api. reactjs error is here (error: has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.)

    response.addHeader("Access-Control-Allow-Origin", "*");
    response.addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, HEAD");
    response.addHeader("Access-Control-Allow-Headers", "X-PINGOTHER, Origin, X-Requested-With, Content-Type, Accept");
    response.addHeader("Access-Control-Max-Age", "1728000");

In tomcat web.xml i add this with bunch of code which is given below. How I can change param-value for multiple client instead of fixed URL like (http://localhost:3000) in tomcat?

<filter>
<filter-name>CorsFilter</filter-name>
<filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
<init-param>
<param-name>cors.allowed.origins</param-name>
<param-value>http://localhost:3000</param-value>
  **(How I can change param-value for multiple client instead of fixed URL)**
</init-param>
<init-param>
<param-name>cors.allowed.methods</param-name>
<param-value>GET,POST,HEAD,OPTIONS,PUT</param-value>
  </init-param>
    <init-param>
     <param-name>cors.allowed.headers</param-name>
     <param-value>Content-Type,X-Requested-With,accept,Origin,Access- 
      Control-Request-Method,Access-Control-Request-Headers</param-value>
  </init-param>
  <init-param>
      <param-name>cors.exposed.headers</param-name>
      <param-value>Access-Control-Allow-Origin,Access-Control-Allow- 
         Credentials</param-value>
  </init-param>
  <init-param>
     <param-name>cors.support.credentials</param-name>
     <param-value>true</param-value>
  </init-param>
  <init-param>
  <param-name>cors.preflight.maxage</param-name>
  <param-value>1800</param-value>
  </init-param>
  </filter>
  <filter-mapping>
  <filter-name>CorsFilter</filter-name>
  <url-pattern>/*</url-pattern>
  </filter-mapping>
Arif Rafsan
  • 91
  • 1
  • 1
  • 8
  • Possible duplicate of [Origin is not allowed by Access-Control-Allow-Origin - how to enable CORS using a very simple web stack and guice](https://stackoverflow.com/questions/16351849/origin-is-not-allowed-by-access-control-allow-origin-how-to-enable-cors-using) – Negi Rox Oct 22 '19 at 10:10

2 Answers2

9

It varies for different Front end apps and back end .... For Emberjs add this line in your corresponding doGet or doPost method..

> response.addHeader("Access-Control-Allow-Origin", "http://localhost:4200");

(or)

> response.addHeader("Access-Control-Allow-Origin", "*"); (for all hosts)

and for Tomcat's web.xml configuration follow these steps that I mentioned below!..

https://tomcat.apache.org/tomcat-7.0-doc/config/filter.html#:~:text=The%20filter%20class%20name%20for%20the%20CORS%20Filter%20is%20org,catalina.

For multiple clients URL just place all URL's by separating a comma's

<filter>
  <filter-name>CorsFilter</filter-name>
  <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
  <init-param>
    <param-name>cors.allowed.origins</param-name>
    <param-value> http://localhost:4200, http://localhost:3000 </param-value>
  </init-param>
</filter>
Thiyagu S
  • 91
  • 1
  • 2
3

You can just create a new filter,

@WebFilter(asyncSupported = true, urlPatterns = { "/*" })
public class CORSInterceptor implements Filter {

    private static final String[] allowedOrigins = {
            "http://localhost:3000", "http://localhost:5500", "http://localhost:5501",
            "http://127.0.0.1:3000", "http://127.0.0.1:5500", "http://127.0.0.1:5501"
    };

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;

        String requestOrigin = request.getHeader("Origin");
        if(isAllowedOrigin(requestOrigin)) {
            // Authorize the origin, all headers, and all methods
            ((HttpServletResponse) servletResponse).addHeader("Access-Control-Allow-Origin", requestOrigin);
            ((HttpServletResponse) servletResponse).addHeader("Access-Control-Allow-Headers", "*");
            ((HttpServletResponse) servletResponse).addHeader("Access-Control-Allow-Methods",
                    "GET, OPTIONS, HEAD, PUT, POST, DELETE");

            HttpServletResponse resp = (HttpServletResponse) servletResponse;

            // CORS handshake (pre-flight request)
            if (request.getMethod().equals("OPTIONS")) {
                resp.setStatus(HttpServletResponse.SC_ACCEPTED);
                return;
            }
        }
        // pass the request along the filter chain
        filterChain.doFilter(request, servletResponse);
    }

    private boolean isAllowedOrigin(String origin){
        for (String allowedOrigin : allowedOrigins) {
            if(origin.equals(allowedOrigin)) return true;
        }
        return false;
    }
}

This will allow all the specified domains, headers, and methods.

  • Do we also need to add `org.apache.catalina.filters.CorsFilter` in web.xml in addition to this filter class? – Moksh Nov 03 '22 at 05:52
  • 1
    No, this is a simple and straightforward solution. You just have to add this class as the first filter in the web.xml file. I suggest that you read more about the CORS concept at https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS – Pratheek Senevirathne Nov 04 '22 at 18:39