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/");
}
};
}
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")