2014-01-31 56 views
0

我使用的是Spring 3.2.2和jQuery。Spring和jQuery POST跨域

一切工作正常在本地。我做了一個CORS過濾器,這也很好。

從另一個主機調用的每個服務方法都在工作,除了一個以外。實際上,這是在客戶端使用@RequestBody$.toJSON/contentType的唯一方法。

彈簧側:

@RequestMapping(value = "/requestOrder", method = RequestMethod.POST) 
@ResponseBody 
public Object requestOrder(@RequestBody OrderViewModel order) throws NamingException { 
    ... 
} 

jQuery的一面:

$.ajax({ 
    type : 'POST', 
    url : serviceUrl + 'requestOrder', 
    crossDomain : true, 
    data : $.toJSON({ ...orderdata... }), 
    contentType : 'application/json; charset=UTF-8' 
}); 

Chrome的控制檯日誌:

XMLHttpRequest cannot load https://REMOTE_HOST/project/service/requestOrder. The request was redirected to 'https://REMOTE_HOST/project/;jsessionid=84781b083f5305ffa22a0adae0a6', which is disallowed for cross-origin requests that require preflight. 

HTTP標頭:

Request URL:https://.../requestOrder 
Request Method:OPTIONS 
Status Code:302 Moved Temporarily 
Request Headersview source 
Accept:*/* 
Accept-Encoding:gzip,deflate,sdch 
Accept-Language:fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4 
Access-Control-Request-Headers:accept, content-type 
Access-Control-Request-Method:POST 
Cache-Control:no-cache 
Connection:keep-alive 
Host:... 
Origin:http://... 
Pragma:no-cache 
Referer:http://... 
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.102 Safari/537.36 

我沒有看到Content-Type應該設置...請求方法是OPTIONS?!

這讓我覺得,這個問題是從春天來但這是本地實際工作...

我會很高興得到一些幫助。

+0

你能後重定向的完整URL對錯誤信息? – renanlf

+0

其實不是正確的,但我會重命名。 –

+0

嘗試在您的RequestMapping中添加produce =「application/json」 – renanlf

回答

0

找到了解決辦法:

我改變了我的Spring MVC方法的參數StringRequestBodyRequestParam:現在

@RequestMapping(value = "/requestOrder", method = RequestMethod.POST) 
@ResponseBody 
public Object requestOrder(@RequestParam("order") String orderJson) { 

Ajax調用是這樣的:

$.ajax({ 
    type : 'POST', 
    url : serviceUrl + 'requestOrder', 
    crossDomain : true, 
    data : { order : $.toJSON({ ...orderdata... }) }, 
    contentType : 'application/json; charset=UTF-8' 
}); 

而在requestOrder方法,我手動解析JSON:

ObjectMapper mapper = new ObjectMapper(); 
OrderViewModel order = mapper.readValue(orderJson, OrderViewModel.class); 
0

您缺少內容類型映射。試試這個

@RequestMapping(value = "/requestOrder", method = RequestMethod.POST, ,headers="Content-Type=application/json") 

對於JQuery的部分 它看起來像你需要同時設置

contentType: 'application/json; charset=utf-8', 
    dataType: 'json', 

Send JSON data with jQuery

+0

不工作。實際上,「Content-Type」頭文件甚至不是由jQuery發送的。 –

1

作用似乎像你需要使用JSONP,如果該請求被beeing做到另一個域。

入住這裏: What is JSONP all about?

+0

感謝您的建議,但實際上,我已經在使用CORS。 –

+0

並且使用JSONP,服務器會拋出'415 Unsupported Media Type' :( –