从Angular Js(Java Web)调用API时出现CORS错误

时间:2017-01-19 04:19:17

标签: java angularjs web-services cors

从Angular Js调用API时出现错误,

XMLHttpRequest cannot load http://10.10.14.54:8080/FcmBackend_ws/rest/devices. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.

我从Web浏览器和Postman调用API时获得了JSON结果。

1 个答案:

答案 0 :(得分:1)

您必须在API中允许原始访问权限,首先您必须定义配置允许的来源和方法的方法:

private void setCrossAccessHeaderResponse(HttpServletResponse servletResponse) {
        servletResponse.setHeader("Access-Control-Allow-Origin", "*"); // Allows all origins
        servletResponse.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
        servletResponse.setHeader("Access-Control-Max-Age", "3600");
        servletResponse.setHeader("Access-Control-Methods", "POST, PUT, OPTIONS, GET, DELETE"); // Define the HTTP verbs allowed
    }

然后你可以从doFilter()方法调用它的方法:

@Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        //We cast the request and response objects
        HttpServletRequest servletRequest = (HttpServletRequest) request;
        HttpServletResponse servletResponse = (HttpServletResponse) response;
        //We set the cross header in response
        setCrossAccessHeaderResponse(servletResponse); // Here we call the method
        boolean isAnRequestBrowser = OPTIONS_METHOD.equals(servletRequest.getMethod());
        if (isAnRequestBrowser) {
            //Do something
        } else {
           // Reject
        }
    }

如果您使用的是Spring,请不要忘记添加@Component注释。

希望它有所帮助。