【问题标题】:XmlHttpRequest No 'Access-Control-Allow-Origin' header is present on the requested resource - Chrome browserXmlHttpRequest 请求的资源上不存在“Access-Control-Allow-Origin”标头 - Chrome 浏览器
【发布时间】:2020-07-28 01:52:40
【问题描述】:

我创建了一个 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/");
            }
        };
    }

【问题讨论】:

  • 控制器添加@CrossOrigin注解。

标签: java spring-boot xmlhttprequest spring-boot-configuration


【解决方案1】:

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

@CrossOrigin(origins = "*")

@CrossOrigin(origins = "http://localhost:8080" , allowCredentials = "true")

【讨论】:

  • 在实施 allowCredentials = "true" 之后,它对我来说工作正常。非常感谢
猜你喜欢
  • 2014-09-22
  • 2015-04-04
  • 2017-08-20
  • 2021-04-09
  • 2017-04-28
  • 2019-10-24
  • 2013-11-29
  • 2014-07-28
相关资源
最近更新 更多