Hello all,
I'm trying to call an external REST service from localhost WAS using Javascript in dynamic web project.
A simple html page includes script
<script>
$.ajaxSetup({
crossDomain: true,
xhrFields: {
withCredentials: true
}
});
$.ajax({
type: "POST",
dataType: "json",
contentType :"application/json",
url: "http://10.77.25.80/WSTest/restservices/WSTest",
data: JSON.stringify(data),
success: function (data) { }
});
</script>
And my web.xml looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" id="WebApp_ID">
<filter-name>CORS</filter-name>
<filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
</filter> <filter-mapping>
<filter-name>CORS</filter-name>
<url-pattern>/*</url-pattern> </filter-mapping>
</web-app>
But i get an error from browser console:
XMLHttpRequest cannot load http://10.77.25.80/WSTest/restservices/WSTest. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9080' is therefore not allowed access.
I 've created a java class CORSFilter and call it from web.xml but i got the same error
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class CORSFilter implements Filter {
public CORSFilter() { }
public void init(FilterConfig fConfig) throws ServletException { }
public void destroy() { }
public void doFilter(
ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
((HttpServletResponse)response).addHeader(
"Access-Control-Allow-Origin", "*"
);
((HttpServletResponse)response).addHeader(
"Access-Control-Allow-Methods", "GET, POST, PATCH, PUT, DELETE, OPTIONS"
);
((HttpServletResponse)response).addHeader(
"Access-Control-Allow-Headers", "origin, x-requested-with, content-type"
);
chain.doFilter(request, response);
}
}
Any idea how to solve this?
I only managed to solve this by adding Chrome extension CORS but its just a temporary solution.
michaeldefox