0

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.

1
  • you can resolve this with two approch 1. set up proxy server or 2. enable cors in your web application. Commented Jan 19, 2017 at 4:58

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

You have to create a class that implements Filter interface, doFilter() is an overrided method. There you can configure the CORS origins.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.