Apache camel CORS问题- REST

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

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

  1. restConfiguration()
  2. .component("servlet")
  3. .bindingMode(RestBindingMode.auto)
  4. .enableCORS(true)
  5. .corsAllowCredentials(true);

实际Rest终点实现

  1. from("rest:post:endpoint1")
  2. //.setHeader("Access-Control-Allow-Credentials",constant( true))
  3. .unmarshal().json(JsonLibrary.Jackson, request.class)
  4. .process(processor);

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

9njqaruj

9njqaruj1#

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

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

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

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

gudnpqoy2#

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

  1. rest("/")
  2. .post("/endpoint1").to("direct:endpoint1");
  3. from("direct:endpoint1")
  4. .unmarshal().json(JsonLibrary.Jackson, request.class)
  5. .process(processor);

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

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

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

  1. curl -v localhost:8080/hello -X POST
  2. < HTTP/1.1 200 OK
  3. < Date: Mon, 11 Apr 2022 11:55:53 GMT
  4. < Accept: */*
  5. < User-Agent: curl/7.79.1
  6. < Transfer-Encoding: chunked
  7. < Server: Jetty(9.4.45.v20220203)
展开查看全部

相关问题