Join the Stack Overflow Community
Stack Overflow is a community of 6.6 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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.

share|improve this question
    
you can resolve this with two approch 1. set up proxy server or 2. enable cors in your web application. – kinkajou 21 hours ago

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.