SmartGWT 数据源和 CORS

SmartGWT Datasource and CORS

我正在使用最新的 Spring 4.1.5 创建一个 RESTful 后端。 Web 服务经过单元测试并且运行良好。我为他们实现了 SimpleCorsFilter 以使这些跨域工作。

public class SimpleCORSFilter implements Filter {

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    HttpServletResponse response = (HttpServletResponse) res;
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
        chain.doFilter(req, res);
    }
    public void init(FilterConfig filterConfig) {}
    public void destroy() {}
}

在使用 SmartGWT RESTDataSource 测试这些 Web 服务之前,我首先使用一些 JavaScript 进行测试。我正在测试三种方法。 第一种方法基于 Whosebug 上的另一个 link,表明这将是确保 SmartGWT 数据源正常工作的良好测试。 当我从浏览器测试此代码时,出现跨脚本错误。

$("#retrieve1").click(function()
{
    $.ajax({
        type : "GET",
        contentType : "application/json",
        url : "http://127.0.0.1:8080/urm-ws-0.0.1-SNAPSHOT/rest/login/user/tholmes/pwd/mypwd",
        dataType : "json",
        crossDomain : true,
        success : function(data, status,xhr) {
            $("#content").text();
        },
        error : function(xhr,status, error) {
            $("#content").text("Unable to retrieve data");
        }
    });
});

但是,接下来的这两种方法可以很好地恢复数据。因此,在这种情况下,我相信 Web 服务将跨域工作。

$("#retrieve2").click(function()
{
    var xhr = new XMLHttpRequest();
    xhr.open('GET','http://127.0.0.1:8080/urm-ws-0.0.1-SNAPSHOT/rest/login/user/tholmes/pwd/mypwd');
    xhr.onreadystatechange = function()
    {
        if (this.status == 200 && this.readyState == 4)
        {
            console.log('response: ' + this.responseText);
        }
    };
    xhr.send();
});

$("#retrieve3").click(function()
{
    $.ajax(
            {
                url : "http://localhost:8080/urm-ws-0.0.1-SNAPSHOT/rest/login/user/tholmes/pwd/mypwd"
            })
    .then(
            function(data) {
                $('#userId').append(data.userId);
                $('#username').append(data.username);
            });

});

我不是很了解 JavaScript,我想知道这三种方法有什么区别?第一种方法由于某种原因不起作用,所以我不知道我是否需要修复该代码,或者我是否需要修复该 JavaScript 方法中的代码?

最终,我想让我的 Web 服务与 SmartGWT 数据源一起工作。我知道这是可以做到的,我觉得我就在那里。 如果我需要提供更多信息,请告诉我。感谢您的帮助。

在第一种情况下浏览器发送 preflighted OPTIONS 请求,因为 application/json 内容类型。我想这个请求在服务器上没有得到正确处理。有关此差异的更多信息,请参见 here

我找到了部分答案:

他们的 CORS 过滤器与我的略有不同。 我有以下内容:

response.setHeader("Access-Control-Allow-Headers", "x-requested-with");

而且确实需要:

response.setHeader("Access-Control-Allow-Headers", "x-requested-with, Content-Type, If-Modified-Since");

一旦我添加了它,第一个 javascript 方法就起作用了,一旦它起作用,我就可以测试我的 SmartGWT 数据源,它与我的远程 RESTful 网络服务一起工作.