0
votes

I have Spring STS installed on my machine and i am creating rest api's in java and accessing it using the url http://localhost:8080/projectname/apiname. I have visual studio installed on the same machine and trying to access the api i created. But when i try to access it in localhost:4200, i am getting the following error.

The Same Origin Policy disallows reading the remote resource at http://localhost:8080/org/getRecord/. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

The same works fine in postman.

I have added the cors allowed origin in my web.xml file

<init-param>
            <param-name>cors.allowed.origins</param-name>
            <param-value>*</param-value>
</init-param>
1
You can use zuul proxy instead of hacking cors. Have a look on this example baeldung.com/spring-rest-with-zuul-proxy - baao

1 Answers

0
votes

Try to adding the filter of your Java Restapi.

Adding the filter.

public class CORSFilter implements Filter {

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    HttpServletResponse response = (HttpServletResponse) res;
    HttpServletRequest request = (HttpServletRequest) req;
    response.setHeader("Access-Control-Allow-Origin", "*"); // allow origin
    response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers", "origin, x-requested-with, content-type, accept, authorization, x-auth-token");

    if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
        response.setStatus(HttpServletResponse.SC_OK);
    } else {
        chain.doFilter(req, res);
    }
  }
}