从 AngularJS 前端到 Spring 其余后端的 CORS 问题

CORS issue from AngularJS frontend to Spring rest backend

我有前端 AngularJS 应用程序和 spring 其余后端应用程序都部署在同一个 tomcat 中,具有相同的端口,它们的上下文不同。我可以从 Postman 访问 spring 个休息端点。但是由于 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? Not http://sbr-devp-55:8080?我必须在 AngularJS 方面做些什么吗?奇怪的是,这在其他 2 个开发人员的 machine.Could 中没有任何 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

报告了 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 位开发人员,检查 header 获得通过的请求是什么,并与您的进行比较?他们的任何代理是否在您的机器中定义?