I have front-end AngularJS application & spring rest back-end application both deployed in the same tomcat with same port, their contexts are different. I can access spring rest endpoints from Postman. But my front-end cannot access the back-end, because of CORS policy. The error message is
Access to XMLHttpRequest at 'http://sbr-devp-55:8080/BackendWS/administration/getLabels' from origin 'http://localhost:8080' 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.
I have tried following approach: writing a CORSFilter as follows:
public class CORSFilter implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers,"
+ " Authorization, X-Requested-With,startTime ");
chain.doFilter(req, res);
}
public void init(FilterConfig filterConfig) {
//initialization code
}
public void destroy() {
//destroy code
}
I have written an initializer like this:
public class BackendWSInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { BackendWSConfiguration.class };
}
@Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
@Override
protected Filter[] getServletFilters() {
Filter [] singleton = { new CORSFilter(),new OpenEntityManagerInViewFilter()};
return singleton;
}
}
What more I need to do? And why the origin is http://localhost:8080? Not http://sbr-devp-55:8080? Do I have to do something at the AngularJS side? And strangely this works without any CORS issue in 2 other developer's machine.Could it be any certificate issue? Error message does not indicate any such thing.
This is how it shows up in F12 > console:
POST http://sbr-devp-55:8080/BackendWS/administration/getLabels 404 (Not Found)
localization.js:108 {data: "", status: 404, headers: ƒ, config: {…}, statusText: "Not Found"}
config: data: {clientId: 92, projectId: 334, languageId: 1, userId: -1}
headers: {Content-Type: "application/json;", Accept: "application/json;", startTime: 1557157292135}method: "POST"
paramSerializer: ƒ ngParamSerializer(params)timeout: 600000
transformRequest: [ƒ]transformResponse: [ƒ]
url: "http://SBR-DEVP-55:8080/BackendWS/administration/getLabels"
__proto__: Objectdata: ""headers: ƒ (name)status: 404statusText: "Not Found"__proto__: Object