1

Ilustration

I'm having this problem, As the picture illustrates.

I have two addresses in Ngrok (Free), one pointing to localhost:4200 (angular) And another pointing to localhost:8080 (Springboot).

So far so good. I put the front pointing to the Ngrok(Back) address to make the requests. POST works, but GET is not working.

It is giving CORS error. I've done everything and I still can't do it.

When I access the backend address through ngrok, it works.

request

On the first request it goes ok. But when you update the front it gives the error.

    @Component
public class CorsFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Max-Age", "7200");
        response.setHeader("Access-Control-Allow-Headers", "Origin, Authorization, Content-Type, xsrf-token, X-Requested-With, Accept, X-Auth-Token");
        response.addHeader("Access-Control-Expose-Headers", "xsrf-token");

        if ("OPTIONS".equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            filterChain.doFilter(request, response);
        }
    }
}
Pradeep Kumar
  • 1,193
  • 1
  • 9
  • 21
  • Seems to be an issue with CORS in the backend with ngrok. Does this [answer](https://stackoverflow.com/a/51879301/13644299) solve the issue ? – Obum Dec 03 '22 at 22:17
  • I can only make requests by POST. The GET I can not. I will try thx! – Rodrigo Leite Dec 03 '22 at 22:54

1 Answers1

1

Spring boot has some security mechanism which let you define CORS (Cross Origin Resource Sharing) security rules

Postman bypasses this mechanism (by using different user agent, and other elements I won't be able to explain), which explains your request working normally when testing with postman.

I strongly recommend you having a look at the Baeldung website, which is great for spring development.

https://www.baeldung.com/spring-cors

There are multiple ways to set up CORS rules in spring, and I don't really know how your project is set up, but you will probably find the right answer to your issue there.

Paul Evans
  • 434
  • 2
  • 13