ishaangupte
ishaangupte

Reputation: 313

@CrossOrigin not working Spring Boot. How can I fix It?

I'm using Spring Boot to make a REST Api for my Vue application. This is my route handler:

@RestController
public class RootController {

    @CrossOrigin
    @GetMapping("/")
    public String index() {
        return "Hello from server";
    }
}

Whenever I use axios to make a request to my API it responds with: enter image description here

How can I fix this?

Upvotes: 0

Views: 3727

Answers (3)

vaibhav0228
vaibhav0228

Reputation: 49

Basically, you need to specify the origin with the @CrossOrigin annotation, that lets the spring app know which all origins are allowed to make request to those rest api's. In your case, you can try replacing @CrossOrigin with @CrossOrigin(origins = "http://localhost:8080") assuming your client application is hosted at port 8080.

Also, you can try @CrossOrigin(origins = "*", allowedHeaders = "*") which would allow every origin and all headers.

Upvotes: 1

hasan.alkhatib
hasan.alkhatib

Reputation: 1559

I would highly recommend that you go to this Spring.io article that covers in-depth what you are asking for!

For the meantime, you can go and create a @Bean that would configure CORS for your application (Consider converting the code into Java syntax, I've just copied it from a kotlin project I'm working on):

@Bean
fun corsFilter(): CorsWebFilter {
    val corsConfig = CorsConfiguration()
    corsConfig.allowedOrigins = Arrays.asList("*")
    corsConfig.maxAge = 8000L
    corsConfig.addAllowedMethod("PUT")
    corsConfig.addAllowedMethod("GET")
    corsConfig.addAllowedMethod("POST")
    corsConfig.addAllowedHeader("Origin")
    corsConfig.addAllowedHeader("Content-Type")
    corsConfig.addAllowedHeader("Accept")

    val source = UrlBasedCorsConfigurationSource()
    source.registerCorsConfiguration("/**", corsConfig)

    return CorsWebFilter(source)
}

Upvotes: 0

Nafaz M N M
Nafaz M N M

Reputation: 1688

@CrossOrigin
@RestController
public class RootController {

    
    @GetMapping("/")
    public String index() {
        return "Hello from server";
    }
}

Upvotes: 0

Related Questions