0

I have an with front and in Vue and back end in spring boot, in the spring boot app I have a controller with 2 endpoints - /api/v1/user/login (POST) and /api/v1/user/get (GET). I have added the @CrossOrigin annotation on the controller. The idea is to make a request to the login endpoint retrieve the jwt token from the response, then call the get endpoint by passing the token in the 'Authorization' header. When I call the login endpoint it works fine and I get the token, however when I call the get endpoint I get a CORS error in chrome like below. I don't know why one endpoint works but the other throws the CORS error.

Access to XMLHttpRequest at 'http://localhost:8082/api/v1/user/get' from origin 'http://localhost:8081' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

I also observed a strange behavior when I checked the Network tab that two requests are going to the get endpoint, one with the 'Authorization' header and other without it. I am not sure why this is happening either.

1 Answers1

0

You have to configure cors in your backend application. With this configuration you should be able to connect with your backend. But you must configure CORS properly in your application. Where has a '*' you must point to the address your frontend is being served.

Suppose you have your vuejs application running in http://localhost:3000 You must configure your cors to point to that address:

 res.addHeader("Access-Control-Allow-Origin", "http://localhost:3000");

In development you should point to the address your frontend is being served.

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class OriginsFilterConfiguration implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletResponse res = (HttpServletResponse) response;
        res.addHeader("Access-Control-Allow-Origin", "*");
        res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
        res.addHeader("Access-Control-Allow-Headers", "Content-Type");
        chain.doFilter(request, response);
    }

}

To know more about cors follow link.

Danizavtz
  • 3,166
  • 4
  • 24
  • 25
  • This is the better solution: https://stackoverflow.com/questions/42016126/cors-issue-no-access-control-allow-origin-header-is-present-on-the-requested/62355755#62355755 – Sathiamoorthy Aug 03 '20 at 09:40