我有前端AngularJS应用程序和spring rest后端应用程序,它们都部署在具有相同端口的同一tomcat中,它们的上下文不同。我可以从Postman访问spring rest端点。但是由于CORS政策,我的前端无法访问后端。错误消息是
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.
我尝试了以下方法:编写CORSFilter如下:
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
}
我写了这样的初始化器:
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;
}
}
我还需要做什么?为何起源是http://localhost:8080?不是http://sbr-devp-55:8080吗?我需要在AngularJS方面做些什么吗?奇怪的是,这在其他2个开发人员的计算机上没有任何CORS问题的情况下都能起作用。错误消息并不表示任何此类情况。
这是它在F12>控制台中的显示方式:
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
答案 0 :(得分:0)
针对XMLHTTP请求报告了类似问题 Why does my JavaScript get a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error when Postman does not?
您在使用Angular <2吗?
对于其他2个开发人员,请检查传递了什么请求标头,然后与您的请求标头进行比较?它们是在您的计算机中定义的任何代理吗?