【问题标题】:How To See What The Problem Is With XmlHttpRequest如何查看 XmlHttpRequest 的问题
【发布时间】:2021-03-06 18:53:38
【问题描述】:

我在 ASP.NET 中编写了一个简单的 REST API,它以 json 格式返回一些数据。然后,我尝试编写一些 javascript 来使用它并碰了壁。当我使用演示 API 时,我的代码可以正常工作,但是当我尝试使用自己的 API 时,它会失败,我不知道如何获取有关原因的任何信息。这是我演示问题的代码(带有 javascript 的 html):

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8" />
        <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
        <meta http-equiv="Pragma" content="no-cache" />
        <meta http-equiv="Expires" content="0" />
    </head>
    <body>
        <h2>Test Output:</h2>
        <div id="testOutput"></div>
    </body>
    
    <script language="javascript">
        function listAllProperties(o) {
            var objectToInspect;     
            var result = [];
        
            for(objectToInspect = o; objectToInspect !== null; 
                   objectToInspect = Object.getPrototypeOf(objectToInspect)) {  
                result = result.concat(
                    Object.getOwnPropertyNames(objectToInspect)
                );  
            }
        
            return result; 
        }
    </script>
    <script language="javascript">
        const testOutput = document.getElementById('testOutput')
    
        var request = new XMLHttpRequest()
        request.open('GET', 'https://ghibliapi.herokuapp.com/films', true)  // with this line, "In Function" is printed
        //request.open('GET', 'http://local.api.com/moviesearch/crash', true)  // ...but if you use this line instead, "In Function" is NOT printed
        request.onload = function () {
            testOutput.innerHTML = "In Function with https://ghibliapi.herokuapp.com/films <br /><br />"
        }
        request.send()
    
        var request2 = new XMLHttpRequest()
        request2.open('GET', 'http://local.api.com/moviesearch/crash', true)  // As stated in the comment above, "In Function" is NOT printed
        request2.onload = function () {
            testOutput.innerHTML += "In Function with http://local.api.com/moviesearch/crash <br /><br />"
        }
    
        function handleEvent(progressEventObject) {
            testOutput.innerHTML += "Failed with http://local.api.com/moviesearch/crash <br /><br />"
            testOutput.innerHTML += "<b>Error Details</b> <br /><br />"
            listAllProperties(progressEventObject).forEach((prop) => testOutput.innerHTML += `${prop} = ${progressEventObject[prop]}<br /><br />`);
            testOutput.innerHTML += "<b>Request Details</b> <br /><br />"
            listAllProperties(progressEventObject.currentTarget).forEach((prop) => testOutput.innerHTML += `${prop} = ${progressEventObject[prop]}<br /><br />`);
        }
    
        request2.addEventListener('error', handleEvent);
        request2.send()
    </script>
    </html>

在“var request = new XMLHttpRequest()”之后的第一段代码中,您可以看到我正在使用“https://ghibliapi.herokuapp.com/films”上的演示 API,这有效,但您可以请参阅下面的“request2”我尝试使用我自己的 API(使用 IIS 在我的本地计算机上运行,​​我可以在本地通过 http://local.api.com/moviesearch/{searchTerm} 访问)。在监视对我编写的 API 的请求时,使用 Firefox 开发人员工具中的“网络”选项卡,我看不到响应有任何问题(原始响应在此处粘贴了标头)。

HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/10.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Tue, 24 Nov 2020 01:11:12 GMT
Content-Length: 69

{"Count":1,"ItemList":["Wedding Crashers 2005 Uncorked Edition"]}

根据 Firefox 开发人员工具中的网络选项卡,此响应在等待 286 毫秒后返回。

我在我的 javascript 结尾处打印的 progressEvent 对象或 XmlHttpRequest 对象中看不到任何有用的东西(但我将粘贴下面的输出,以防它有助于调试它)。

错误详情:

"isTrusted" = "true"
"lengthComputable" = "false"
"loaded" = "0"
"total" = "0"
"constructor" = "function ProgressEvent() { [native code] }"
"composedPath" = "function composedPath() { [native code] }"
"stopPropagation" = "function stopPropagation() { [native code] }"
"stopImmediatePropagation" = "function stopImmediatePropagation() { [native code] }"
"preventDefault" = "function preventDefault() { [native code] }"
"initEvent" = "function initEvent() { [native code] }"
"type" = "error"
"target" = "[object XMLHttpRequest]"
"srcElement" = "[object XMLHttpRequest]"
"currentTarget" = "[object XMLHttpRequest]"
"eventPhase" = "2"
"bubbles" = "false"
"cancelable" = "false"
"returnValue" = "true"
"defaultPrevented" = "false"
"composed" = "false"
"timeStamp" = "382"
"cancelBubble" = "false"
"originalTarget" = "[object XMLHttpRequest]"
"explicitOriginalTarget" = "[object XMLHttpRequest]"
"NONE" = "0"
"CAPTURING_PHASE" = "1"
"AT_TARGET" = "2"
"BUBBLING_PHASE" = "3"
"ALT_MASK" = "1"
"CONTROL_MASK" = "2"
"SHIFT_MASK" = "4"
"META_MASK" = "8"
"constructor" = "function ProgressEvent() { [native code] }"
"toString" = "function toString() { [native code] }"
"toLocaleString" = "function toLocaleString() { [native code] }"
"valueOf" = "function valueOf() { [native code] }"
"hasOwnProperty" = "function hasOwnProperty() { [native code] }"
"isPrototypeOf" = "function isPrototypeOf() { [native code] }"
"propertyIsEnumerable" = "function propertyIsEnumerable() { [native code] }"
"__defineGetter__" = "function __defineGetter__() { [native code] }"
"__defineSetter__" = "function __defineSetter__() { [native code] }"
"__lookupGetter__" = "function __lookupGetter__() { [native code] }"
"__lookupSetter__" = "function __lookupSetter__() { [native code] }"
"__proto__" = "[object ProgressEvent]"
"constructor" = "function ProgressEvent() { [native code] }"

请求详情:

"open" = "undefined"
"setRequestHeader" = "undefined"
"send" = "undefined"
"abort" = "undefined"
"getResponseHeader" = "undefined"
"getAllResponseHeaders" = "undefined"
"overrideMimeType" = "undefined"
"onreadystatechange" = "undefined"
"readyState" = "undefined"
"timeout" = "undefined"
"withCredentials" = "undefined"
"upload" = "undefined"
"responseURL" = "undefined"
"status" = "undefined"
"statusText" = "undefined"
"responseType" = "undefined"
"response" = "undefined"
"responseText" = "undefined"
"responseXML" = "undefined"
"mozAnon" = "undefined"
"mozSystem" = "undefined"
"UNSENT" = "undefined"
"OPENED" = "undefined"
"HEADERS_RECEIVED" = "undefined"
"LOADING" = "undefined"
"DONE" = "undefined"
"constructor" = "function ProgressEvent() { [native code] }"
"onloadstart" = "undefined"
"onprogress" = "undefined"
"onabort" = "undefined"
"onerror" = "undefined"
"onload" = "undefined"
"ontimeout" = "undefined"
"onloadend" = "undefined"
"constructor" = "function ProgressEvent() { [native code] }"
"addEventListener" = "undefined"
"removeEventListener" = "undefined"
"dispatchEvent" = "undefined"
"constructor" = "function ProgressEvent() { [native code] }"
"toString" = "function toString() { [native code] }"
"toLocaleString" = "function toLocaleString() { [native code] }"
"valueOf" = "function valueOf() { [native code] }"
"hasOwnProperty" = "function hasOwnProperty() { [native code] }"
"isPrototypeOf" = "function isPrototypeOf() { [native code] }"
"propertyIsEnumerable" = "function propertyIsEnumerable() { [native code] }"
"__defineGetter__" = "function __defineGetter__() { [native code] }"
"__defineSetter__" = "function __defineSetter__() { [native code] }"
"__lookupGetter__" = "function __lookupGetter__() { [native code] }"
"__lookupSetter__" = "function __lookupSetter__() { [native code] }"
"__proto__" = "[object ProgressEvent]"
"constructor" = "function ProgressEvent() { [native code] }"

最后,当对我的 API 的请求导致错误事件侦听器函数被调用时,我看到没有任何内容写入浏览器控制台。

感谢您抽出宝贵时间阅读本文以及您可以就如何继续向我提供的任何提示。

【问题讨论】:

  • 您是否能够使这些错误/请求详细信息可读而无需向右滚动 3 英里?
  • 您在浏览器开发者工具控制台中看到任何错误吗?
  • 嗯,这是一个非常好的建议,可以查看开发人员工具控制台。这告诉我这是一个 CORS 错误,具体如下:“跨域请求被阻止:同源策略不允许读取localhost/moviesearch/crash 的远程资源。(原因:CORS 标头‘Access-Control-Allow-Origin’缺失) 。”谢谢!
  • 所以这是服务器代码问题,而不是客户端代码问题

标签: javascript json rest xmlhttprequest firefox-developer-tools


【解决方案1】:

正如 Bravo 在他们的评论中建议的那样,我检查了开发工具控制台并看到了 CORS 错误:

“跨域请求被阻止:同源策略不允许 在 localhost/moviesearch/crash 读取远程资源。 (原因: CORS 标头‘Access-Control-Allow-Origin’缺失)。”

以下帖子中的答案是这个问题的一个非常棒/简单的解决方案: Setting Access-Control-Allow-Origin in ASP.Net MVC - simplest possible method

谢谢你!

【讨论】:

    猜你喜欢
    • 2017-02-10
    • 2011-02-05
    • 1970-01-01
    • 1970-01-01
    • 2011-09-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多