3

这是一个相当古老的问题,但是在尝试了我学到的所有东西之后,在尝试通过 CORS POST 请求发送 JSON 数据数小时后,我仍然无法使其正常运行。带有参数的 GET 和 POST 运行良好,但 POST 数据似乎难以捉摸。

您不会在此处的代码中看到它,但是为所有 servlet 设置了 CORS 过滤器映射。我认为这不是我无法从 ajax 请求中访问控制器方法的原因。

环境:

  • jQuery:1.8.2
  • 铬:版本 23.0.1271.64 m
  • Spring MVC 3.0.5.RELEASE

我尝试使用 httprequest 软件,所以我知道如果我可以将以下请求发送到服务器,它会正常工作。但是我不能使用默认的 Content-type 发送请求,所以我从来没有在飞行前发送真正的请求

从服务器获得正确响应所需的请求:

POST http://localhost:8068/web-app/app/api/post-json-obj
Content-Type: application/json
{"description": "hello", "title": "JohnDoe", "identifier":"testResponse"}

代码:

<html>
<head>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>

<script type="application/javascript">   
//Required Request Info:
//POST http://localhost:8068/web-app/app/api/post-json-obj
//Content-Type: application/json
//{"description": "hello", "title": "JohnDoe", "identifier":"testResponse"}

(function($) {
var url = 'http://localhost:8068/web-app/app/api/post-json-obj';
var data = {"description": "hello", "title": "JohnDoe", "identifier":"testResponse"};
$.ajax({
type: 'POST',
url: url,
data: JSON.stringify(data),
contentType:"application/json",
success: function(response) {
alert("success");
},
error: function(xhr) {
alert('Error!  Status = ' + xhr.status + " Message = " + xhr.statusText);
}
});
})(jQuery);
</script>
</head>
<body>

</body>
</html>

服务器端:

  @RequestMapping(value="/post-json-obj", method = RequestMethod.POST, consumes = {"application/json"})
      public @ResponseBody ResponseEntity<WebResponse> postJSONObject(@RequestBody Item item) {
          WebResponse res = new WebResponse();
          res.setMessage("success");    
  return new ResponseEntity<WebResponse>(res, HttpStatus.ACCEPTED);
  }

飞行前:

要求

OPTIONS /web-app/app/api/post-json-obj HTTP/1.1
Host: localhost:8068
User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:16.0) Gecko/20100101 Firefox/16.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
DNT: 1
Connection: keep-alive
Origin: http://localhost
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type
Pragma: no-cache
Cache-Control: no-cache

回复

  HTTP/1.1 200 OK
  Server: Apache-Coyote/1.1
  Access-Control-Allow-Origin: *
  Access-Control-Allow-Methods: GET, POST, PUT, DELETE
  Access-Control-Allow-Headers: Content-Type
  Access-Control-Max-Age: 1800
  Allow: GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS
  Content-Length: 0
  Date: Wed, 14 Nov 2012 20:27:37 GMT

真实要求

要求:

  POST http://localhost:8068/web-app/app/api/post-json-obj HTTP/1.1

请求负载:{"name":"hello","message":"JohnDoe"}

回复:

没有反应

4

0 回答 0