【问题标题】:How to Get the Custom Error Response Text in the HTTP 403 Response如何在 HTTP 403 响应中获取自定义错误响应文本
【发布时间】:2020-01-14 13:38:36
【问题描述】:

我使用以下方法发出 AJAX 请求:

function getJSON(url, callback) {
    var xhr = new XMLHttpRequest();
    xhr.open("GET", url, true);
    xhr.responseType = "json";
    xhr.onload = function() {
        if (xhr.status === 200) {
            callback(null, xhr.response);
        } 
        else {
            /*var errorObj = { status: xhr.status, statusText: xhr.statusText };
            callback(errorObj, xhr.response);*/
            callback(xhr.status, xhr.response);
        }
    };
    xhr.send();
};

如果状态为 403,我必须从服务器获取自定义响应文本。xhr.response 为空,尽管我可以在 Chromium 调试器窗口的“网络”选项卡中看到自定义错误消息。如何访问自定义响应文本?

【问题讨论】:

  • 可能是responseText 属性?
  • 试试 responseText。 (如果对方基于此返回不同的响应,也可能删除 responseType)
  • else 分支中将responseType 设置为text?很久没用XHR了……
  • 我在成功分支中使用了 JSON.parse(xhr.response)。谢谢你们的帮助。

标签: javascript ajax http-status-code-403


【解决方案1】:

试试这个:

  if (xhr.status === 200) {
            callback(null, xhr.response);
        } else if(xhr.status === 403){
            callback(xhr.status, "not found =(");
         }
        else {
            /*var errorObj = { status: xhr.status, statusText: xhr.statusText };
            callback(errorObj, xhr.response);*/
            callback(xhr.status, xhr.response);
        }

【讨论】:

    【解决方案2】:

    xhr.responseText 应该是诀窍

    【讨论】:

    • 嗨,欢迎来到堆栈溢出。为了得到一个有用的答案,这个反应需要扩展。解释为什么这是问题的答案。
    猜你喜欢
    • 1970-01-01
    • 2014-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-08
    • 2018-01-29
    • 1970-01-01
    相关资源
    最近更新 更多