BaseX REST API: Set custom HTTP response header

冷暖自知 提交于 2021-02-08 04:54:09

问题


I want to include the following HTTP header to all responses by the BaseX REST API:

Access-Control-Allow-Origin: *

Is this possible?


回答1:


BaseX uses Jetty below the hood. You can modify the web.xml file to make Jetty send CORS headers, but either

  • use at least BaseX 8.6.3 which added the jetty-servlets library or
  • have to add the jetty-servlets jar to your $CLASSPATH (BaseX already ships jetty-servlet, which is a different class; and be sure to fetch the appropriate version matching what's included in BaseX).

Include following directives to the web.xml file:

<web-app>
    <!-- add those before the closing web-app tag: -->
    <filter>
        <filter-name>cross-origin</filter-name>
        <filter-class>org.eclipse.jetty.servlets.CrossOriginFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>cross-origin</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

Be aware that Jetty does not seem to support posting a wildcard header Access-Control-Allow-Origin: *: while the default is already

<init-param>
     <param-name>allowedOrigins</param-name>
     <param-value>*</param-value>
</init-param>

(put that into the <filter/> element), Jetty uses this to construct a regular expression and always returns the value of the Origin: request header if matching, but that should also serve you well.

An example request:

$ curl -v -H "Origin: http://foo.example" http://admin:admin@localhost:8984/rest
*   Trying ::1...
* Connected to localhost (::1) port 8984 (#0)
* Server auth using Basic with user 'admin'
> GET /rest HTTP/1.1
> Host: localhost:8984
> Authorization: Basic YWRtaW46YWRtaW4=
> User-Agent: curl/7.50.1
> Accept: */*
> Origin: http://foo.example
> 
< HTTP/1.1 200 OK
< Content-Type: application/xml; charset=UTF-8
< Content-Length: 152
< Server: Jetty(8.1.18.v20150929)
< 
<rest:databases xmlns:rest="http://basex.org/rest" resources="1">
  <rest:database resources="1" size="96234589">test</rest:database>
</rest:databases>
* Connection #0 to host localhost left intact

Given this seems a rather reasonable request and thing to do, you might be successful opening an issue to include the library by default, and maybe even enabling CORS by default. (the library is now included by default)



来源:https://stackoverflow.com/questions/42932689/basex-rest-api-set-custom-http-response-header

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!