在dropwizard和jquery上使用CORS时出现问题

时间:2014-04-30 18:28:07

标签: jquery cors dropwizard

无法让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中设置错误

2 个答案:

答案 0 :(得分:0)

您可以创建一个Web过滤器来解决此问题,Jetty有一个Cross Origin Filter,您可以使用此过滤器。

答案 1 :(得分:0)

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

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