我在自定义休息端点设置“Access-Control-Allow-Origin”,但是当我从javascript调用此web服务时,我收到以下错误
XMLHttpRequest cannot load http://10.239.12.22:8042/LATEST/resources/repoUIFacet?rs:q=TNF. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://gprulcd707873.abbvienet.com:8000' is therefore not allowed access. The response had HTTP status code 401.
以下是我设置响应标头的代码
(: Function responding to GET method - must use local name 'get':)
declare function repoUIFacet:get($context as map:map, $params as map:map) as document-node()*
{
let $output-types := map:put($context,"output-types","application/json")
let $_ := xdmp:add-response-header("Access-Control-Allow-Origin", "*")
...
};
如何为OPTIONS请求设置响应标头?
答案 0 :(得分:2)
错误消息以The response had HTTP status code 401
结尾。这是身份验证的问题,而不是访问控制头。您需要发送凭据,或将应用服务器切换到应用级身份验证。
HTH!
答案 1 :(得分:2)
我最近遇到了类似的问题。在从浏览器发出请求时,浏览器向MarkLogic发送另一个OPTIONS请求。但是我的路由器检查了api_key,如果它不存在,我用40x代码回复。
在检查api密钥之前,只要传入方法是OPTIONS,就可以使用200代码重新编码。所有其他方法检查api并返回相应的响应代码。
e.g。如果你使用xquery路由器,你可以尝试这样的事情:
let $method := fn:lower-case(xdmp:get-request-method())
(: Intercept OPTIONS method and respond immediately :)
if ($methods = 'options') then
xdmp:set-response-code(200, 'OK')
else (:
invoke the endpoint function "$method", e.g. repoUIFacet:get
:)
祝你好运!
答案 2 :(得分:2)
如果有人有兴趣,请按照以下步骤操作,而不是在MarkLogic自定义rest-api前面编写自定义Web服务层。
我基本上有一个Apache服务器充当自定义Marklogic端点的代理。然后我为它设置CORS标头..并且还捕获OPTIONS请求并发送200 ..只是让你知道,当请求有授权时。 '*'Access-Control-Allow-Origin *
,将无法工作..你需要指定主机..我做了一个正则表达式的解决方法,以下是我在apache配置或.htaccess文件中的做法
<IfModule mod_headers.c>
SetEnvIf Origin "^http(s)?://(.+\.)?(YOUR_DOMAIN.com)(:[0-9]+)?$" origin_is=$0
Header always set Access-Control-Allow-Origin %{origin_is}e env=origin_is
Header always set Access-Control-Allow-Methods "POST, GET, PUT, DELETE, OPTIONS"
Header always set Access-Control-Max-Age "1000"
Header always set Access-Control-Allow-Headers "X-Requested-With, content-type, Access-Control-Allow-Origin, Authorization, X-User-Id"
</IfModule>
RewriteEngine on
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$ $1 [R=200,L]
ProxyPass /cr_dev http://10.239.12.22:8042/LATEST/resources
ProxyPassReverse /cr_dev/ http://10.239.12.22:8042/LATEST/resources