-1

I'm working with Java + Spring + PHPmyadmin and pure HTML + JS on my first API and trying to understand how ajax works and the problem is that I succeded doing a POST, PUT and DELETE but when I'm trying to do a GET by id ajax (similarly to the DELETE one) chrome is returning me the CORS error

Access to XMLHttpRequest at 'http://localhost:8081/dices/players/id?{%22id%22:%22408%22}' from origin 'http://localhost' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource".

I don't understand why I'm getting this ONLY when I try the GET, and the other actions work fine... Also the full 'back part' of the API works fine and has been tested with POSTMAN. Here is my CORS Filter in Java ( I don't know exactly how it works 100%):

@Component
public class SimpleCORSFilter implements Filter {
    private final Logger log = LoggerFactory.getLogger(SimpleCORSFilter.class);
    public SimpleCORSFilter() {
        log.info("SimpleCORSFilter init");
    }
    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Credentials", "true");
        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, Content-Type, Accept, X-HTTP-Method-Override, X-Requested-With, remember-me");
        chain.doFilter(req, res);
    }
    @Override
    public void init(FilterConfig filterConfig) {
    }
}

And here is my function in JS (almost the same as DELETE by id that is working fine)

//GET PLAYER BY ID

function getById() {

    let playerID = document.getElementById("playerID").value;

        let playerToShow = {
            id: playerID,
        }

        let shownPlayer = JSON.stringify(playerToShow);

        $.ajax({
            type: "GET",
            url: "http://localhost:8081/dices/players/id",
            contentType: "application/json",
            data: shownPlayer, 
            success: function (data) {

                document.getElementById("data").innerHTML = JSON.stringify(data);
                console.log(data);
            },
            error: function () {

                alert("Something went wrong!);
            }
        });
    } 
}

I'm pretty lost with all this CORS thing so I'll thank you all for any clue you may have! Thanks and sorry for my English!

Jaykooh
  • 63
  • 1
  • 8
  • What’s the HTTP status code of the response? You can use the Network pane in browser devtools to check. Is it a 4xx or 5xx error rather than a 200 OK success response? – sideshowbarker May 08 '20 at 12:08
  • Take a look here: https://stackoverflow.com/questions/43871637/no-access-control-allow-origin-header-is-present-on-the-requested-resource-whe?rq=1 – sonan May 08 '20 at 12:21
  • @sideshowbarker it just says 'failed' :S with type "xhr" – Jaykooh May 08 '20 at 12:32
  • What does the Network pane in Firefox devtools show? – sideshowbarker May 08 '20 at 12:35
  • In the Console pane in Chrome devtools, do you have **Log XMLHttpRequests** checked? – sideshowbarker May 08 '20 at 12:36
  • @sideshowbarker it wasn't checked but now it is checked and still returning the same problem... – Jaykooh May 08 '20 at 13:13
  • After you’ve turned **Log XMLHttpRequests** on, what requests and responses are now being logged in the console, and what are the status codes? – sideshowbarker May 08 '20 at 14:17
  • @sideshowbarker request and responses are the same in console... also status, nothing changed. – Jaykooh May 08 '20 at 16:10
  • I viewed in a video that it's possible to use (dataType: "jsonp") and "jump" the CORS problem I have, but I don't know if it is "cheating" someway or what. Whatever, with this included in my ajax request the response in console now is: "jquery.min.js:4 GET http://localhost:8081/dices/players/id?callback=jQuery22406585324331433429_1588955375022&{%22id%22:%22410%22}&_=1588955375024 net::ERR_ABORTED 400" – Jaykooh May 08 '20 at 16:37

2 Answers2

1

I think I've got it. You need to pass in query string parameters, not JSON data, into the GET.

let shownPlayer = $.param(playerToShow);

stringify - "{\"id\":\"1234\"}"

param - "id=1234"

tinymothbrain
  • 412
  • 2
  • 6
  • Now the problem with CORS seems to be solved! $.param works similarly to JSONP? I would like to understand how it works. Whatever, now I have a GET 400 error, any new clue? haha, thanks anyway! – Jaykooh May 08 '20 at 17:26
  • 1
    You can put JSON data into the body of a GET request, but the code you had was putting the JSON stringified data into the query string. http://localhost/dices/player/id?"{\"id\":\"1234\"}" – tinymothbrain May 08 '20 at 17:33
  • You can look at the AJAX request in the console and see the request data and URL that should show you what is going on. I will add what the difference is in the answer. – tinymothbrain May 08 '20 at 17:37
  • What does the 400 error look like? I guess you could ask another question. – tinymothbrain May 08 '20 at 17:39
  • but I used the same JSON with DELETE by id and it worked fine, without CORS troubles and getting the correct object of my DB, it should have caused the same issues right? – Jaykooh May 08 '20 at 17:40
  • this is the actual error --> GET "http://localhost:8081/dices/players/id?id=410" 400 – Jaykooh May 08 '20 at 17:41
  • I'm really noob and I don't have the binary log tab to see logs in phpmyadmin... I'm a bit confused, you know another form to get it? :S – Jaykooh May 08 '20 at 17:53
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/213438/discussion-between-tinymothbrain-and-jaykooh). – tinymothbrain May 08 '20 at 17:55
0

Try adding this to your doFilter method just before the chain.doFilter line

if (request.getMethod().equals("OPTIONS")) {
    resp.setStatus(HttpServletResponse.SC_OK);
    return;
}
tinymothbrain
  • 412
  • 2
  • 6