英文:
XmlHttpRequest No 'Access-Control-Allow-Origin' header is present on the requested resource - Chrome browser
问题
我已经创建了一个Java服务来返回一个JSON对象。在Postman中它运行正常,但是当我尝试在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/");
}
};
}
英文:
I have created a java service to return a json object. It is working fine in postman but when i try it using the chrome browser i am getting below error
> CORS policy issue
the code:
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();
Error:
Spring boot java service main function:
@Bean
public WebMvcConfigurer configure() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry corsRegistry) {
corsRegistry.addMapping("/**").allowedOrigins("http://localhost:8080/");
}
};
}
答案1
得分: 0
Sure, here's the translated code part:
你需要让你的控制器知道请求的来源。
要解决跨域问题,请在你的控制器中添加以下代码。
你可以尝试使用通配符,像这样:
@CrossOrigin(origins = "*")
或者
@CrossOrigin(origins = "http://localhost:8080", allowCredentials = "true")
英文:
You need allow your controller to know about the origin of the request.
To Fix cors issue add below code to your controller.
You can try with wild card like
@CrossOrigin(origins = "*")
or
@CrossOrigin(origins = "http://localhost:8080" , allowCredentials = "true")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论