Overview
Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional HTTP headers to tell browsers to give a web application running at one origin, access to selected resources from a different origin. All modern browsers support it. Nowadays, most web pages are single-page applications (SPAs). It means that you can run a frontend application separately from the backend application in debug mode. CORS prevents you from this. In this case, you may want to temporarily turn it off. In the post, we are going to discuss how to turn off CORS for a Spring server application.
Turn off CORS
If you don’t use Spring security then you could easily turn off CORS.
Simply add the following code:
1
2
3
4
5
6
7
8
9
10
11
12
13
/*
* Dissable CORS
*/
@Profile("dev")
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
}
I also recommend using Spring Profiles to easily enable and disable it.
Conclusion
We have discussed how to turn off CORS for a Spring server application.