TechiRik
TechiRik

Reputation: 2143

Where to enable cors?

I have a very basic question.

I have an application www.myapp1.com hosted on tomcat server. It in turn calls apis hosted on myapis.com/api1 on apache server.

While loading the page, it breaks stating -

XMLHttpRequest cannot load myapis.com/api1. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'www.myapp1.com' is therefore not allowed access. The response had HTTP status code 403.

I understand I have to enable CORS. My question is which server do I enable CORS on? Should it be www.myapp1.com or myapis.com/api1?

I tried enabling CORS on www.myapp1.com, which is a tomcat7.0.59 server by adding the minimal filter (below) to /config/web.xml file and restarting the server. However, it is not working. Do I need to add/configure anything else?

<filter>
  <filter-name>CorsFilter</filter-name>
  <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
</filter>
<filter-mapping>
  <filter-name>CorsFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

Is the wildcard in url-pattern causing a problem? Do I have to do anything to setup the filter-class?

I am using chrome to test. Please help.

Upvotes: 1

Views: 2883

Answers (1)

Beck Yang
Beck Yang

Reputation: 3024

The default value of cors.exposed.headers is "". Add this parameter could fix the issue.

<filter>
  <filter-name>CorsFilter</filter-name>
  <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
  <init-param>
    <param-name>cors.exposed.headers</param-name>
    <param-value>Access-Control-Allow-Origin,Access-Control-Allow-Credentials</param-value>
  </init-param>
</filter>

Upvotes: 1

Related Questions