working with Java 11, eclipse, Gradle and spring in an ubuntu os
While my POST calls are working fine, the GET calls to the server are blocked due to the CORS policy with below error:
Access to XMLHttpRequest at 'http://localhost:8080/dices/players?{}' 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.
the javascript for the POST and GET calls is:
$(document).ready(function(){
$('#newUserButton').click(function(){
$.ajax({
type: 'POST',
url: 'http://localhost:8080/dices/players',
contentType: 'application/json',
xhrFields: { withCredentials: true },
data: JSON.stringify({"name":$('#newUserInput').val()}),
dataType: 'json',
success: function(data) {
$('#newUserJumbo').append('<div class="alert alert-success" role="alert">El usuari ' + data.name + ' ha estat creat</div>');
},
error: function(e){
console.log(e);
}
});
});
});
$(document).ready(function(){
$('#searchUserButton').click(function(){
$.ajax({
type: 'GET',
url: 'http://localhost:8080/dices/players',
contentType: 'application/json',
xhrFields: { withCredentials: true },
data: JSON.stringify({"idPlayer":$('searchUserInput').val()}),
dataType: 'json',
success: function(data) {
$('#modifyUserUl').append('<button type="button" class="list-group-item list-group-item-action" id="' + data.id + ' onclick=modifyUser(' + data.id + '>id: ' + data.id + ', nom: ' + data.name + '</button>');
},
error: function(e){
console.log(e);
}
});
});
});
To handle the CORS at server side, i'm using the below class that i've found in a mozilla mdnwebDoc here which is working fine with the POST call, but fails on the GET
the code that handles the GET call is as follows:
@CrossOrigin(origins = "http://lvh.me:8080")
@GetMapping("/players/player")
public Player getPlayer(@RequestBody Player newPlayer){
try {
return (Player) repository.findFirstByNameLike(newPlayer.getName());
} catch (EmptyResultDataAccessException e) {
throw new PlayerNotFoundException(newPlayer.getName());
UPDATE 1
As Albert commented, i've changed the http://localhost to http://lvh.me to see if by this, the code works, but no exit. Also i have edited my controller code changing from @PathVariable to @RequestBody (as my POST request to the same controller with a json body is working) also with effect. Fiinally, thanks to Kevin comments, i've also changed the way to handle the CORS policy from a global approach to a controller approach, also without exit. i've changed the code above to reflec this changes.
Any comments & suggestions are welcome. Thanks thanks