0

我创建了一个 java 服务来返回一个 json 对象。它在邮递员中工作正常,但是当我使用 chrome 浏览器尝试它时,我遇到了错误

CORS 政策问题

编码:

var xhttp = new XMLHttpRequest();
var url = 'http://localhost:8030/information/agent111';
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
       console.log(this)
    }
};
xhttp.open("GET", url, true);
xhttp.setRequestHeader('Content-Type', 'application/json' );
xhttp.setRequestHeader('Access-Control-Allow-Origin', 'http://localhost:8080');
xhttp.setRequestHeader('Access-Control-Allow-Headers', 'http://localhost:8080');
xhttp.setRequestHeader('Access-Control-Allow-Methods', 'GET');
xhttp.setRequestHeader('Access-Control-Allow-Credentials', false);
xhttp.send();

错误:

在此处输入图像描述

Spring Boot java服务主要功能:

@Bean
    public WebMvcConfigurer configure() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry corsRegistry) {
                corsRegistry.addMapping("/**").allowedOrigins("http://localhost:8080/");
            }
        };
    }
4

1 回答 1

0

您需要让您的控制器知道请求的来源。要修复 cors 问题,请将以下代码添加到您的控制器。您可以尝试使用通配符

@CrossOrigin(origins = "*")

或者

@CrossOrigin(origins = "http://localhost:8080" , allowCredentials = "true")
于 2020-07-27T16:45:36.140 回答