1

服务器已被修改以发送正确的请求标头。

服务器 - 响应标头:

Access-Control-Max-Age: 86400
Access-Control-Allow-Methods: GET, OPTIONS, POST
Access-Control-Allow-Origin: * 
Access-Control-Allow-Headers: Content-Type, X-Requested-With

我正在为服务器(a.foo.com)使用 Spring web mvc,并使用 mvc 拦截器来设置 HttpResponseHeaders。

我还尝试将来源设置为请求的域,而不是“*”。

客户端 - jQuery 代码

我正在使用 jQuery/AJAX - jquery 1.7.1 这是 POST 请求的摘要。

var settings = {};
settings.url = "http://a.foo.com/api";
settings.type = 'POST';
settings.data = JSON.stringify(request);
settings.dataType = 'json';
settings.contentType = 'application/json; charset=utf-8';
settings.crossDomain = true; // adding or removing this, didn't make a difference
.... (setup callbacks etc)
jQuery.ajax(settings);

该网站 - html/js 托管在 a.bar.com

客户端出错 - javascript 控制台(在 chrome 上测试)

XMLHttpRequest 无法加载http://a.foo.com/api。Access-Control-Allow-Origin 不允许来源http://a.bar.com 。

问题

还有什么我想念的吗?我想避免使用 JSONP,主要是因为我需要 POST 支持。

感谢您的任何指示,以及您的帮助。

4

1 回答 1

1

I didn't have the response headers set for the OPTIONS request. I was setting it for the GET/POST requests.

Following this blog helped: http://zhentao-li.blogspot.com/2012/06/enable-cors-support-in-rest-services.html

Now when I hit the endpoint (a.foo.com/api/*) with the request method OPTIONS/GET/POST, I get the following headers:

Date: Wed, 08 Aug 2012 02:58:05 GMT  
Connection: keep-alive  
Content-Length: 0   
Allow: GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS   
Server: Apache-Coyote/1.1   
Access-Control-Max-Age: 1800  
Access-Control-Allow-Methods: GET, POST, PUT, DELETE  
Content-Type: text/plain; charset=UTF-8   
Access-Control-Allow-Origin: *  
Access-Control-Allow-Headers: Content-Type

I tested this out on Chrome. I wonder if there will be issues with IE! :) I'd like for this to work with IE9 as well, but from what I read, I shouldn't get my hopes up.

Thanks @Strelok for your suggestions. And @sth and @xdazz.

于 2012-08-08T18:33:06.223 回答