【问题标题】:trouble with CORS on dropwizard and jquerydropwizard和jquery上的CORS问题
【发布时间】:2015-03-18 19:47:11
【问题描述】:

无法让 CORS 与 Dropwizard 和 jquery 一起使用。

在 Dropwizard 上设置:

environment.addFilter(CrossOriginFilter.class, "*")
  .setInitParam("allowedOrigins", "*")
  .setInitParam("allowedHeaders", "X-Requested-With,Content-Type,Accept,Origin,Access-Control-Request-Method,Authorization,Access-Control-Request-Method")
  .setInitParam("allowedMethods", "OPTIONS,GET,PUT,POST,DELETE,HEAD");

在客户端:

$.ajax({ // create an AJAX call...
                beforeSend: function(xhr, settings) {
                    var csrftoken = getCookie('csrftoken');
                    xhr.setRequestHeader("X-CSRFToken", csrftoken);
                },
                data: {'taduID': taduId }, // get the form data
                crossDomain: true,
                type: 'POST',
                url: 'http://0.0.0.0:8080/tadu/getTaduFromId?id' + taduId,
                success: function(response) { // on success..
                    console.log(response);          
                }
            });
            return false;

但是在 chrome 中得到这个:

XMLHttpRequest cannot load http://0.0.0.0:8080/tadu/getTaduFromId?id94339742-4381-46f2-b004-38a2d73b68bf. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:8000' is therefore not allowed access. 

这里是请求/响应

Remote Address:0.0.0.0:8080
Request URL:http://0.0.0.0:8080/tadu/getTaduFromId?id94339742-4381-46f2-b004-38a2d73b68bf
Request Method:OPTIONS
Status Code:204 No Content
Request Headersview source
Accept:*/*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:accept, x-csrftoken, content-type
Access-Control-Request-Method:POST
Connection:keep-alive
Host:0.0.0.0:8080
Origin:http://127.0.0.1:8000
Referer:http://127.0.0.1:8000/m/
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.116 Safari/537.36
Query String Parametersview sourceview URL encoded
id94339742-4381-46f2-b004-38a2d73b68bf:
Response Headersview source
Allow:OPTIONS,GET,HEAD
Date:Wed, 30 Apr 2014 18:23:24 GMT

我确定这里有很多错误,但从哪里开始呢?有预感我在 Dropwizard 中设置了一些错误

【问题讨论】:

    标签: jquery cors dropwizard


    【解决方案1】:

    你可以创建一个网络过滤器来解决这个问题,码头有一个跨域过滤器你可以使用这个过滤器。

    【讨论】:

    • 我认为这就是 environment.addFilter(... 正在做的事情,但它似乎没有任何效果。
    • 您使用哪个版本的 dropwizard?在 v0.6.2 或更低版本中,jetty cors 过滤器不起作用,您需要创建一个 Web 过滤器,您可以查看此链接:spring.io/guides/gs/rest-service-cors 此示例使用 Spring more filter is equals in Dropwizard。
    【解决方案2】:

    您收到 HTTP 状态 204(无内容)的响应。 你确定/tadu/getTaduFromId?id94339742-4381-46f2-b004-38a2d73b68bf实际上返回的任何内容不是void方法吗?

    除此之外,您的 CORS 过滤器看起来是正确的,您可以通过多种方式实现自己的过滤器并根据您使用的 Dropwizard 版本进行注册。

    【讨论】:

      猜你喜欢
      • 2021-08-04
      • 1970-01-01
      • 2013-11-05
      • 1970-01-01
      • 2014-10-15
      • 2018-07-12
      • 2015-12-16
      • 2015-08-20
      • 2015-06-16
      相关资源
      最近更新 更多