-1

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

1 Answers1

1

You can specifically enable CORS for that endpoint using the following:

@CrossOrigin(origins = "http://localhost:8080")
@GetMapping("/players/{idPlayer}")
public Player getPlayer(@PathVariable Integer idPlayer){
    try {
        return (Player) repository.findById(idPlayer);
    } catch (EmptyResultDataAccessException e) {
        throw new PlayerNotFoundException(idPlayer);
    }
}

If you want to address CORS at a global level you need to create a WebMvcConfigurer bean in the class with your main method:

@SpringBootApplication
public class YourApplication {

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**").allowedOrigins("http://localhost:8080");
            }
        };
    }
}
Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
  • Thanks @Kevin, i've removed the WebMvcConfigurer when i got the POST calls working, as i believed that was not necessary while using the simpleCorsFilter() class. i've added it again to the application but the same error is returned from server"Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/dices/players?{}. (Reason: CORS preflight response did not succeed)." – Raul Magdalena Catala Feb 19 '20 at 10:49