0

我尝试使用 WSO2 DAS 3.0 REST API 从我的商店中检索一些数据。该 API 使用 SoapUI 或 Chrome 扩展 REST 客户端可以正常工作。然而,使用 JQuery 的 Ajax 从 javascript 调用它在同源策略上失败。

如文档中所述,我将过滤器添加到服务器端的 web.xml 中:

    <filter>
    <filter-name>CorsFilter</filter-name>
    <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
    <init-param>
        <param-name>cors.allowed.origins</param-name>
        <param-value>*</param-value>
    </init-param>
    <init-param>
        <param-name>cors.allowed.methods</param-name>
        <param-value>GET,POST,HEAD,OPTIONS,PUT,DELETE,PATCH</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>CorsFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

调用如下所示:

    $.ajax({
    url: 'https://localhost:9443/analytics/search',
    type: 'POST',
    data: {
        "tableName":"TEST",
        "query":"*:*",
        "start":0,
        "count":100
    },
    headers: {
        Authorization: 'Basic YWRtaW46YWRtaW4=',
    },
    dataType: 'json',
    success: function (data) {
        alert(1);
        //console.info(data);
    }
});

但是,从错误消息中可见,未应用允许的来源:

XMLHttpRequest cannot load https://localhost:9443/analytics/search. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://myserver' is therefore not allowed access. The response had HTTP status code 403.

有人使用 JQuery 成功调用 API 吗?

4

1 回答 1

2

答案就像向服务器端过滤器添加一个额外的参数一样简单,因为 JQuery 倾向于在预检请求中发送与允许来源相关的标头。配置应如下所示:

<filter>
    <filter-name>CorsFilter</filter-name>
    <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
    <init-param>
        <param-name>cors.allowed.origins</param-name>
        <param-value>*</param-value>
    </init-param>
    <init-param>
        <param-name>cors.allowed.methods</param-name>
        <param-value>GET,POST,HEAD,OPTIONS,PUT,DELETE,PATCH</param-value>
    </init-param>
    <init-param>
        <param-name>cors.allowed.headers</param-name>
        <param-value>Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,authorization</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>CorsFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
于 2015-12-15T16:06:46.900 回答