简体   繁体   中英

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

I am getting an error while call the API from Angular Js,

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.

You have to allow origin access in your API, first you have to define a method configuring the allowed origins and methods:

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:

@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.

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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