0

我想通过 POST 方法向 REST Web 服务发出 Ajax 请求并从中获取数据,当使用 Postman 时,请求工作正常,但如果我使用像 ExtJS 6 这样的 JavaScript 框架不起作用,则 Web 服务在 java并且在远程服务器上。我在网络浏览器上收到 CORS 政策错误。在服务器 WildFly 11 上配置了 CORS 过滤器。如何在不被 CORS 阻止的情况下从服务中获取数据?

这是我正在做的请求

...
Ext.Ajax.request({
            url: 'url-to-my-web-service/method1',
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            cors: true,
            useDefaultXhrHeader: false,
            withCredentials: true,
            params : {
                "user": "xxxx@xxxx.com",
                "pwd": "xzxzxzxz"
            },
            success: function(conn, response, options, eOpts) {
                var result = conn.responseText;
                console.log("success...!");
            },
            failure: function(conn, response, options, eOpts) {
                // TODO get the 'msg' from the json and display it
                console.log("error..!");
            }
        });
...

在 WildFly 11 (standalone.xml) 中

<subsystem xmlns="urn:jboss:domain:undertow:4.0">
            <buffer-cache name="default"/>
            <server name="default-server">
                <http-listener name="default" socket-binding="http" redirect-socket="https" enable-http2="true"/>
                <https-listener name="https" socket-binding="https" security-realm="ApplicationRealm" enable-http2="true"/>
                <host name="default-host" alias="localhost">
                    <location name="/" handler="welcome-content"/>
                    <filter-ref name="server-header"/>
                    <filter-ref name="x-powered-by-header"/>
                    <filter-ref name="Access-Control-Allow-Origin"/>
                    <filter-ref name="Access-Control-Allow-Methods"/>
                    <filter-ref name="Access-Control-Allow-Headers"/>
                    <http-invoker security-realm="ApplicationRealm"/>
                </host>
            </server>
            <servlet-container name="default">
                <jsp-config/>
                <websockets/>
            </servlet-container>
            <handlers>
                <file name="welcome-content" path="${jboss.home.dir}/welcome-content"/>
        </handlers>
            <filters>
                <response-header name="server-header" header-name="Server" header-value="WildFly/11"/>
                <response-header name="x-powered-by-header" header-name="X-Powered-By" header-value="Undertow/1"/>
                <response-header name="Access-Control-Allow-Origin" header-name="Access-Control-Allow-Origin" header-value="*"/>
                <response-header name="Access-Control-Allow-Methods" header-name="Access-Control-Allow-Methods" header-value="GET, POST, OPTIONS, PUT"/>
                <response-header name="Access-Control-Allow-Headers" header-name="Access-Control-Allow-Headers" header-value="accept, authorization,  content-type, x-requested-with"/>
            </filters>
</subsystem>

Java 代码(ws 类)

...
Interface interface = new ImpInterface();
    @OPTIONS
    @Consumes("application/json")
    @Path("/method1")
    public Response getToken(String clientData){
        return interface.method1(clientData);
    }
    }
...

界面

public interface Interface  {
    public Response method1(String clientData);
}

方法1

public Response method1(String clientData) {
        ...
        try {
        ...
            jsonResponse = new JSONObject().put("test", objectTest).put("value", objectTest2).toString();

            return Response
                    .status(Response.Status.OK)
                    .entity(jsonResponse)
                    .header("Access-Control-Allow-Origin", "*")
                    .header("Access-Control-Allow-Credentials", "true")
                    .header("Access-Control-Allow-Headers", "origin, content-type, accept, authorization")
                    .header("Access-Control-Allow-Methods", "POST, OPTIONS")
                    .build();

        } catch (Exception e) {
            ...
            return exception;
        }
}

Web浏览器控制台中的错误

Access to XMLHttpRequest at 'url-to-my-web-service/method1' from origin 'null' has been 
blocked by CORS policy: Cross origin requests are only supported for protocol schemes: 
http, data, chrome, chrome-extension, https.

4

1 回答 1

0

首先:将OPTIONS处理程序添加到您的Java Code (ws class). 像这样:

Interface interface = new ImpInterface();
    @OPTIONS
    @Consumes("application/json")
    @Path("/method1")
    public Response getToken(String clientData){
        return Response.status(201).entity("")
        .header("Access-Control-Allow-Origin", "*")
        .header("Access-Control-Allow-Credentials", "true")
        .header("Access-Control-Allow-Headers", "origin, content-type, accept, authorization")
        .header("Access-Control-Allow-Methods", "POST, OPTIONS")
        .build();
    }

下一个 :standalone.xml

<subsystem xmlns="urn:jboss:domain:undertow:4.0">
            <buffer-cache name="default"/>
            <server name="default-server">
                <http-listener name="default" socket-binding="http" redirect-socket="https" enable-http2="true"/>
                <https-listener name="https" socket-binding="https" security-realm="ApplicationRealm" enable-http2="true"/>
                <host name="default-host" alias="localhost">
                    <location name="/" handler="welcome-content"/>
                    <filter-ref name="server-header"/>
                    <filter-ref name="x-powered-by-header"/>
                    <filter-ref name="Access-Control-Allow-Origin"/>
                    <filter-ref name="Access-Control-Allow-Methods"/>
                    <filter-ref name="Access-Control-Allow-Headers"/>
                    <filter-ref name="Access-Control-Allow-Credentials"/> 
                    <filter-ref name="Access-Control-Max-Age"/>
                    <http-invoker security-realm="ApplicationRealm"/>
                </host>
            </server>
            <servlet-container name="default">
                <jsp-config/>
                <websockets/>
            </servlet-container>
            <handlers>
                <file name="welcome-content" path="${jboss.home.dir}/welcome-content"/>
        </handlers>
            <filters>
                <response-header name="server-header" header-name="Server" header-value="WildFly/11"/>
                <response-header name="x-powered-by-header" header-name="X-Powered-By" header-value="Undertow/1"/>
                <response-header name="Access-Control-Allow-Origin" header-name="Access-Control-Allow-Origin" header-value="*"/>
                <response-header name="Access-Control-Allow-Methods" header-name="Access-Control-Allow-Methods" header-value="GET, POST, OPTIONS, PUT"/>
                <response-header name="Access-Control-Allow-Headers" header-name="Access-Control-Allow-Headers" header-value="accept, authorization,  content-type, x-requested-with"/>
                <response-header name="Access-Control-Allow-Credentials" header-name="Access-Control-Allow-Credentials" header-value="true"/>
                <response-header name="Access-Control-Max-Age" header-name="Access-Control-Max-Age" header-value="1"/>
            </filters>
</subsystem>

withCredentials在应用程序中,您应该trueExt.Ajax.request.

withCredentials 信息

XMLHttpRequest.withCredentials 属性是一个布尔值,指示是否应使用 cookie、授权标头或 TLS 客户端证书等凭据进行跨站点访问控制请求。设置 withCredentials 对同站点请求没有影响。

Sencha withCredentials 文档

使用跨域资源共享时,有时需要此配置。

例子:

Ext.Ajax.request({
            withCredentials: true,
            url: 'url-to-my-web-service/method1',
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            cors: true,
            useDefaultXhrHeader: false,
            params : {
                "user": "xxxx@xxxx.com",
                "pwd": "xzxzxzxz"
            },
            success: function(conn, response, options, eOpts) {
                var result = conn.responseText;
                console.log("success...!");
            },
            failure: function(conn, response, options, eOpts) {
                // TODO get the 'msg' from the json and display it
                console.log("error..!");
            }
        });
于 2019-04-02T09:50:21.543 回答