Cross-origin HTTP Request
If your front-end web UI and back-end restful API are stored in different domains, such as:
Due to security reason, web browser will return you with the below error:
Please note that even different ports will treat as different origin.
In order to allow different domains calling the restful API, you can either:
1) override the addCorsMappings (CorsRegistry registry) method. You can find the below settings under com.itblogs.config.AppConfiguration, which contains Spring configuration and bean definitions.
//<mvc:cors>
// <mvc:mapping path=”/**”
// allowed-origins=”http://localhost:8181″
// allowed-methods=”GET, POST, PUT, DELETE, OPTIONS”
// allowed-headers=”*”
// exposed-headers=”*”
// allow-credentials=”false”
// max-age=”3600″ />
//</mvc:cors>
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping(“/**”)
.allowedOrigins(“http://localhost:8181”)
.allowedMethods(“GET”, “POST”, “PUT”, “DELETE”, “OPTIONS”)
//.allowedHeaders(“header1”, “header2”, “header3”)
//.exposedHeaders(“header1”, “header2”)
.allowCredentials(false).maxAge(3600);
}
2) or, adding @CrossOrigin annotation to the method(s) of your controller, such as:
But, in this case, you may need to define @CrossOrigin to all of your controllers’ methods.