Apache camel CORS问题- REST

oewdyzsn  于 2022-11-07  发布在  Apache
关注(0)|答案(2)|浏览(251)

我遇到了Apache camel REST API CORS的问题,它是GET请求的工作,但不是其他方法。

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

实际Rest终点实现

from("rest:post:endpoint1")

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

当添加头到请求的其余部分时,它为GET请求工作。

9njqaruj

9njqaruj1#

您可能需要指定更多内容,例如

  • 允许的方法列表
  • 允许的源列表

这可以通过使用adhoc HTTP头来完成:

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

gudnpqoy2#

旧的Rest组件可能不支持它,因为它仅用于基本用例。
对于像CORS这样的高级功能,您需要使用Rest DSL定义您的休息端点,如下所示:

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

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

使用完全相同的Rest配置(enableCORS(true)),但使用Rest DSL定义的端点,无论使用何种HTTP方法,CORS HTTP头都会自动添加到HTTP响应中。
以下是使用Rest DSL定义的POST端点的HTTP响应标头

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)

以下是使用旧的Rest组件定义的POST端点的HTTP响应头

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)

相关问题