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