我正在尝试使用此jQuery代码生成Ajax CORS请求
$.ajax({
url: "http://localhost:8080/itt_service/rest",
type: "POST",
contentType: "application/json;charset=utf-8",
data: pdata,
dataType: "text"
}).done(function(data){})
.always(function (a,data,b) {})
.fail(function (jqXHR, textStatus, errorThrown) {
alert("Failed: " + errorThrown);});
但始终执行失败功能,无需进一步说明。 查看浏览器的“网络”部分,我可以看到首先出现了预期的OPTIONS预检请求。 请求标头是:
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.5
Access-Control-Request-Headers: content-type
Access-Control-Request-Method: POST
Connection: keep-alive
Host: localhost:8080
Origin: http://localhost:8383
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:59.0) Gecko/20100101 Firefox/59.0
,响应标题为:
HTTP/1.1 200 OK
Access-Control-Allow-Headers: content-type
Access-Control-Allow-Methods: POST
Access-Control-Allow-Origin: *
Content-Length: 0
Date: Sat, 21 Apr 2018 10:19:30 GMT
Server: GlassFish Server Open Source Edition 4.1
X-Powered-By: Servlet/3.1 JSP/2.3 (GlassFish Server Open Source Edition 4.1 Java/Oracle Corporation/1.8)
一切看起来都不错,而且必须如此,因为此预检请求后面跟着实际的POST请求。请求标头现在是
Accept: application/json, text/javascript, */*; q=0.01
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.5
Connection: keep-alive
Content-Length: 79
Content-Type: application/json;charset=utf-8
Host: localhost:8080
Origin: http://localhost:8383
Referer: http://localhost:8383/itt_webclient/main.html
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:59.0) Gecko/20100101 Firefox/59.0
,响应标题为
HTTP/1.1 200 OK
Content-Length: 27
Content-Type: application/json;charset=utf-8
Date: Sat, 21 Apr 2018 10:19:30 GMT
Server: GlassFish Server Open Source Edition 4.1
X-Powered-By: Servlet/3.1 JSP/2.3 (GlassFish Server Open Source Edition 4.1 Java/Oracle Corporation/1.8)
一切看起来还不错。我得到200 OK,我得到正确的Content-Length(27),我甚至可以在浏览器的网络工具中看到响应主体:
{"results":{},"errors":[8]}
(不要介意"错误"身体的反应,它是预期的正确反应) 但是从不调用done处理程序。而是始终使用" textStatus"来调用失败处理程序:"错误"和" errorThrown":""。 CORS部分对我来说没问题,我想如果cors协商失败,第二个POST请求根本就不会发生。我还可以通过更改" Access-Control-Allow-Origin"来检查它。来自服务器的响应"错误",这导致没有按预期的POST请求。 我想知道JSON响应是否在某种程度上没有形成,所以我也将预期的响应类型(在客户端和服务器上)更改为" text / plain",但问题仍然存在。 我也尝试使用XMLHttpRequest而不是jQuery来发出请求,结果相同。
你知道吗? 感谢