【问题标题】:CORS policy error with Java + Spring in an ajax queryajax 查询中 Java + Spring 的 CORS 策略错误
【发布时间】:2020-06-03 11:01:42
【问题描述】:

在 ubuntu 操作系统中使用 Java 11、eclipse、Gradle 和 spring

虽然我的 POST 调用工作正常,但由于 CORS 策略,对服务器的 GET 调用被阻止并出现以下错误:

通过“http://localhost:8080/dices/players?{}”访问 XMLHttpRequest 来自原点“http://localhost”已被 CORS 策略阻止: 对预检请求的响应未通过访问控制检查:否 请求中存在“Access-Control-Allow-Origin”标头 资源。

POST 和 GET 调用的 javascript 是:

$(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);
            }
        });
    });
});

为了在服务器端处理 CORS,我使用了我在 mozilla mdnwebDoc here 中找到的以下类,该类在 POST 调用中运行良好,但在 GET 上失败

处理GET调用的代码如下:

    @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());

更新 1

正如 Albert 评论的那样,我已将 http://localhost 更改为 http://lvh.me 以查看代码是否有效,但没有退出。 我还编辑了从@PathVariable 更改为@RequestBody 的控制器代码(因为我对具有json 主体的同一个控制器的POST 请求正在工作)也有效。 最后,感谢 Kevin cmets,我还改变了处理 CORS 策略的方式,从全局方法到控制器方法,也没有退出。 我已更改上面的代码以反映此更改。

欢迎任何 cmets 和建议。谢谢 谢谢

【问题讨论】:

    标签: java jquery spring gradle cors


    【解决方案1】:

    您可以使用以下方法专门为该端点启用 CORS:

    @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);
        }
    }
    

    如果您想在全局级别解决 CORS,您需要使用您的 main 方法在类中创建一个 WebMvcConfigurer bean:

    @SpringBootApplication
    public class YourApplication {
    
        @Bean
        public WebMvcConfigurer corsConfigurer() {
            return new WebMvcConfigurer() {
                @Override
                public void addCorsMappings(CorsRegistry registry) {
                    registry.addMapping("/**").allowedOrigins("http://localhost:8080");
                }
            };
        }
    }
    

    【讨论】:

    • 感谢@Kevin,当我让 POST 调用正常工作时,我已经删除了 WebMvcConfigurer,因为我认为在使用 simpleCorsFilter() 类时没有必要这样做。我已将其再次添加到应用程序,但服务器返回相同的错误“Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at localhost:8080/dices/players?{}。(原因:CORS 预检响应未成功)。”
    猜你喜欢
    • 1970-01-01
    • 2021-08-14
    • 2020-05-02
    • 2021-12-19
    • 1970-01-01
    • 2021-11-02
    • 1970-01-01
    • 2021-11-14
    • 1970-01-01
    相关资源
    最近更新 更多