'Apache camel CORS Issue- REST

I am having trouble with Apache camel REST API CORS , It is working for GET request but not for other methods.

restConfiguration()
    .component("servlet")
    .bindingMode(RestBindingMode.auto)
    .enableCORS(true)
    .corsAllowCredentials(true);

Actual Rest end point implementation

from("rest:post:endpoint1")

    //.setHeader("Access-Control-Allow-Credentials",constant( true))
    .unmarshal().json(JsonLibrary.Jackson, request.class)
    .process(processor);

When adding header to rest request it working for GET request.



Solution 1:[1]

You probably need to specify more things, eg

  • the list of allowed methods
  • the list of allowed origins

This can be done using adhoc HTTP headers:

.setHeader("Access-Control-Allow-Origin", constant("*") )
.setHeader("Access-Control-Allow-Methods", constant("GET, POST, OPTIONS") )

Solution 2:[2]

It is likely not supported by the old Rest component as it is only meant to be used for basic use cases.

For advanced features like CORS, you need to define your rest endpoints using the Rest DSL as next:

rest("/")
    .post("/endpoint1").to("direct:endpoint1");

from("direct:endpoint1")
    .unmarshal().json(JsonLibrary.Jackson, request.class)
    .process(processor);

With the exact same Rest configuration (enableCORS(true)) but with your endpoint defined with the Rest DSL, the CORS HTTP headers will automatically be added to your HTTP responses whatever the HTTP method used.

Here are the HTTP response headers of a POST endpoint defined using the Rest DSL:

curl -v localhost:8080/say -X POST  

< HTTP/1.1 200 OK
< Date: Mon, 11 Apr 2022 11:55:57 GMT
< Content-Type: application/json
< Accept: */*
< Access-Control-Allow-Headers: Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers
< Access-Control-Allow-Methods: GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, CONNECT, PATCH
< Access-Control-Allow-Origin: *
< Access-Control-Max-Age: 3600
< User-Agent: curl/7.79.1
< Transfer-Encoding: chunked
< Server: Jetty(9.4.45.v20220203)

Here are the HTTP response headers of a POST endpoint defined using the old Rest component:

curl -v localhost:8080/hello -X POST

< HTTP/1.1 200 OK
< Date: Mon, 11 Apr 2022 11:55:53 GMT
< Accept: */*
< User-Agent: curl/7.79.1
< Transfer-Encoding: chunked
< Server: Jetty(9.4.45.v20220203)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 TacheDeChoco
Solution 2