how to enable cors request on springboot application
Enabling CORS in a Spring Boot Application
To enable CORS (Cross-Origin Resource Sharing) in a Spring Boot application, you can follow these steps:
Add the necessary dependencies: In your
pom.xml
file, add the following dependencies:xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
Configure CORS globally: Create a new class, let's call it
CorsConfig
, and annotate it with@Configuration
. Inside the class, define a bean of typeWebMvcConfigurer
and override theaddCorsMappings
method to configure CORS globally. Here's an example: ```java import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/")
.allowedOrigins("")
.allowedMethods("GET", "POST", "PUT", "DELETE")
.allowedHeaders("")
.allowCredentials(true)
.maxAge(3600);
}
}
``
In this example, we allow all origins (
*`), specify the allowed HTTP methods, allow all headers, enable credentials, and set the maximum age of the CORS configuration to 3600 seconds (1 hour). You can customize these settings according to your requirements.
- Enable CORS for specific controllers: If you want to enable CORS for specific controllers only, you can use the
@CrossOrigin
annotation at the class or method level. For example: ```java import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController;
@RestController
@CrossOrigin(origins = "http://localhost:8080")
public class MyController {
@GetMapping("/api/data")
public String getData() {
// ...
}
}
``
In this example, the
@CrossOriginannotation allows requests from
http://localhost:8080to access the
/api/data` endpoint.
That's it! With these steps, you have enabled CORS in your Spring Boot application. Now, your application will respond to cross-origin requests according to the configured CORS settings.