No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
This is because of the Same Origin Policy – it says that every AJAX request must match the exact host, protocol, and port of your site.
How to fix it:
Simply just provide access to all the host, protocol, and port by using *.
Modify the server to add the header Access-Control-Allow-Origin: * to enable cross-origin requests from anywhere (or specify a domain instead of *).
This should solve your problem.
In you projects web.xml add the following filter
<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>*</param-value>
</init-param>
<init-param>
<param-name>cors.allowed.methods</param-name>
<param-value>GET, POST, PUT, DELETE, OPTIONS, HEAD</param-value>
</init-param>
</filter>
Now for limiting the access to only specific host, protocol, or port you can use the following param-value
<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>*</param-value> -->
<param-value>http://localhost:4000,https://myapp.com</param-value>
</init-param>
<init-param>
<param-name>cors.allowed.methods</param-name>
<param-value>GET, POST, PUT, DELETE, OPTIONS, HEAD</param-value>
</init-param>
</filter>
Now here is this case only the requests from the following urls will be allowed while other will throw a CORS error even if they have a slight change in host, protocol, or port
http://localhost:4000 and https://myapp.com
FYI in above
http , https --> protocols
localhost , myapp -> hosts
4000 --> port