我使用XmlHttpRequest向服务器发送请求。请求在服务器上处理,服务器希望发送错误 答案与解释性文本(在正文中)。我尝试了很多不同的响应代码,但在客户端(Chrome v33左右)上,XHR对象的响应始终为空。
客户端:
var formItem = document.forms.namedItem("regform"),
formData = null;
/* -----------------------------------------------------------------
* General validation - after all the above
* ----------------------------------------------------------------- */
if (! formItem.checkValidity())
{
setup_register();
return;
}
formData = new FormData(formItem);
var req = new XMLHttpRequest(),
url = "http://" + host + "...whatever.../registration";
console.log("Start Registration " + formData);
req.open("POST", url, true);
req.onreadystatechange = function () {
if (this.readyState == 4)
{
if (this.status == 200)
{
console.log("Registration finished OK");
window.return_window.postMessage("Done", '*');
window.close();
}
else
{
console.error("Registration failed" + req.status + " Text:" + req.responseText);
return;
}
}
};
req.send(formData);
服务器:
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Path("/registration")
public ClientIdentification registration(
@FormDataParam("username") String username,
@FormDataParam("firstname") String firstname,
@FormDataParam("password") String password,
@FormDataParam("lastname") String lastname,
@FormDataParam("verifypassword") String verifypassword,
@FormDataParam("businessname") String businessname,
...
...
throw new PisRsMessageException(e.getMessage(), HttpServletResponse.SC_FORBIDDEN);
其中PisRsMessageException是一个简单的包装器aound Jersy的WebApplicationException
我已经嗅到这个,以确保正确发送响应。但是req.responseText始终为空。
我看到这或多或少是对W3C标准的简单解释 - 如果服务器返回错误,responseText应为空。这没有用。我需要有一种方法来返回错误,但仍然有解释性文本。
请参阅:http://www.w3.org/TR/2014/WD-XMLHttpRequest-20140130/#the-responsetext-attribute
后备将始终返回200,但如果没有必要,我不想这样做。
答案 0 :(得分:0)
在发生错误的情况下,我似乎忘记了CORS标头,这就是Chrome消除响应文本的原因。