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!
2
Answers
Try adding this to your doFilter method just before the chain.doFilter line
I think I’ve got it. You need to pass in query string parameters, not JSON data, into the GET.
stringify – “{“id”:”1234″}”
param – “id=1234”