Spring和jQuery POST交叉域

时间:2014-01-31 12:44:49

标签: java javascript jquery spring spring-mvc

我正在使用Spring 3.2.2和jQuery。

一切都在当地运作良好。我做了一个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?!

这让我觉得问题来自Spring,但这实际上是在本地工作......

我很乐意得到一些帮助。

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

似乎您需要使用JSONP,如果此请求是针对另一个域的。

点击此处: What is JSONP all about?

答案 2 :(得分:0)

找到解决方案:

我将我的Spring mvc方法的参数更改为String,将RequestBody更改为RequestParam

@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);