简体   繁体   English

从Angular Js(Java Web)调用API时发生CORS错误

[英]CORS error while API calling from Angular Js (Java web)

I am getting an error while call the API from Angular Js, 从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.

I am getting the JSON result while calling the API from a web browser and from Postman. 从网络浏览器和Postman调用API时,我得到JSON结果。

You have to allow origin access in your API, first you have to define a method configuring the allowed origins and methods: 您必须在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
    }

then you can call it method from the doFilter() method: 那么您可以从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
        }
    }

If you're using Spring, don't forget to put the @Component annotation. 如果您使用的是Spring,请不要忘记添加@Component批注。

Hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM