【发布时间】:2020-11-21 12:52:41
【问题描述】:
我正在使用登录表单来构造和发送一个 URL(即下面脚本中写入存储的“完整 url”),该 URL 应该返回一个 JSON 对象。
如果登录正确,后端会向我发送一个带有验证密钥的 JSON 对象,以验证它是否成功返回。 (像这样:[{"result":"VALID"}])
如果登录不正确,只会提供500错误。
不幸的是,当它收到 500 错误时,并没有因为结果无效而启动它们,而是因为没有要验证的对象而放弃了脚本。
如何从前端检测到收到 500 错误然后触发“bootThem()”?
function readTextFile(file, callback) {
var rawFile = new XMLHttpRequest();
rawFile.overrideMimeType("application/json");
rawFile.open("GET", file, true);
rawFile.onreadystatechange = function () {
if (rawFile.readyState === 4 && rawFile.status == "200") {
callback(rawFile.responseText);
}
}
rawFile.send(null);
}
window.onload = function () {
// get the url from storage.
var fullURL = localStorage.getItem("fullURLStored")
// if the URL is empty, boot them back to the login page.
if(fullURL == " "){
bootThem();
}
// send the URL to the server.
readTextFile(fullURL, function (text) {
var data = JSON.parse(text);
if(data[0].result !== "VALID"){
bootThem();
} else{
//do stuff
}
});
}
【问题讨论】:
-
if (rawFile.readyState === 4 && rawFile.status == "200") {
标签: javascript json error-handling http-status-code-500