I've been delving into Java, Spring, PHPmyadmin, and a combination of pure HTML and JS for my first API project. I've managed to successfully implement POST, PUT, and DELETE requests, but I'm encountering an issue with GET requests by ID using AJAX. Chrome keeps showing me a 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 find it puzzling that this issue occurs only with GET requests while other actions work flawlessly. The backend part of the API functions smoothly and has been verified with POSTMAN. Below is the CORS Filter in Java (I still have some uncertainties about its functionality):
@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) {
}
}
Also included below is my function in JS (similar to the working DELETE by id function) that's causing the CORS error:
//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!);
}
});
}
}
The complex nature of CORS is leaving me perplexed, so any insights or suggestions would be greatly appreciated! Thank you in advance, and apologies for any language errors!