我正在使用Angular2对servlet进行POST调用。现在我必须使用servlet。servlet在响应中返回JSON,但Angular将所有响应显示为失败,因为响应包含
"在JSON响应中,而不是“。我在控制台中看到:
xhrstatusText: {"status":"OK"}
replaced statusTest={"status":"OK"}我不确定问题出在servlet还是Angular调用上。
Servlet
public void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
JsonObject jsonObj = Json.createObjectBuilder().add("status", "OK").build();
response.setStatus(HttpServletResponse.SC_OK, jsonObj.toString());
}Angular2 POST呼叫
makeFileRequest(params: Array<string>, files: Array<File>) {
return new Promise((resolve, reject) => {
var formData: any = new FormData();
var xhr = new XMLHttpRequest();
for(var i = 0; i < files.length; i++) {
formData.append("uploads[]", files[i], files[i].name);
}
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
// Contains " instead of " in JSON.
console.log('xhrstatusText: ' + xhr.statusText);
// This fixes the JSON, but the response is already marked as failed.
var statusTextJson = xhr.statusText.replace(/("\;)/g,"\"");
console.log('replaced statusTest=' + statusTextJson);
if (xhr.status == 200) {
resolve(JSON.parse(xhr.response));
} else {
reject(xhr.response);
}
}
}
xhr.open("POST", this.url, true);
xhr.send(formData);
});
}!!!最终解决方案!
Servlet
public void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.setStatus(HttpServletResponse.SC_OK);
JsonObject jsonObj = Json.createObjectBuilder().add("status", "OK").build();
response.getWriter().println(jsonObj.toString());
}Angular2 POST呼叫
makeFileRequest(params: Array<string>, files: Array<File>) {
return new Promise((resolve, reject) => {
var formData: any = new FormData();
var xhr = new XMLHttpRequest();
for(var i = 0; i < files.length; i++) {
formData.append("uploads[]", files[i], files[i].name);
}
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
// {"status":"OK"}
console.log('xhr.response: ' + xhr.response);
if (xhr.status == 200) {
resolve(JSON.parse(xhr.response));
} else {
reject(xhr.response);
}
}
}
xhr.open("POST", this.url, true);
xhr.send(formData);
});
}发布于 2016-11-01 01:04:29
根据HttpServletResponse的javadoc,setStatus(int, String)方法实际上已经因为这个原因而被弃用(第二个参数用途不明确)。它并不是真的想做你想做的事情。
相反,可以考虑简单地使用setStatus(int)方法设置状态,并将JsonObject写入响应的打印编写器:
response.setStatus(HttpServletResponse.SC_OK);
response.getWriter().println(jsonObj.toString());https://stackoverflow.com/questions/40346845
复制相似问题