【问题标题】:JS Ajax request produces error on localhost but not on web serverJS Ajax 请求在本地主机上产生错误,但在 Web 服务器上不产生错误
【发布时间】:2019-03-26 23:31:12
【问题描述】:

总结

使用相同的代码(在 asp.net 核心站点中),跨不同浏览器,当浏览到页面的本地主机 IIS 版本时,XMLHttpRequest 检测到某种错误并调用其错误事件并将状态设置为零,尽管有成功读取数据(网络显示200 OK)并存入responseText。

在生产/登台网络服务器上,代码每次都能正常运行。

由于某种原因,纯文本文件在本地似乎也可以正常工作(严格来说,它们是由早期的中间件处理的),但生成的内容(HTML 和 JSON)带有正常的标头会产生错误。

我的问题是:为什么它现在会产生这个错误,而以前没有?

在下面回答...

完整的原始帖子

直到最近(2-3 天前)使用 jQuery 的 $.get() 的 AJAX 调用在我的开发机器上以及在暂存/生产环境中都可以正常工作。

从昨天(当我注意到时)开始,AJAX 调用现在在站点的 localhost 版本上失败,而在生产版本上可以正常工作。

我已经在 Firefox、Edge 和 Opera 中尝试过 - 都得到了相同的结果。我生成了最精简的代码,并且仍然可以产生相同的错误结果 - 这几乎完全排除了我的代码。

我查看了 Firefox 和 Edge 的发行说明,找不到任何与我相关的内容。

本地主机正在使用自签名测试证书,该证书在 Firefox 中存在异常。暂存站点具有真正的第 3 方签名证书。

整个页面代码为:

<html>
  <head>
    <style>@media print {#ghostery-purple-box {display:none !important}}</style>
  </head>
  <body>
    <h1>hi</h1>
    <script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
  </body>
</html>

然后我在每个浏览器的控制台窗口中运行这个 javascript:

$.ajax({url:'/Test',error:function(a,b,c){alert(b)}, success:function(a){alert(a);}});

请原谅格式,单行用于更简单的复制/粘贴和测试。

我能想到的每个配置的输出是 alert(b) 部分运行,b 等于“错误”。

两种配置的唯一区别是网址:

https://localhost:44300/Test

对

https://[productionfqdn]:444/Test

从网络服务器返回的标头,本地是 IIS Express,远程是 IIS——两者都由 Kestrel 支持,因为它是 ASP.NET Core 站点的一部分——尽管我已经排除了其中任何一个可能是问题(在我意识到这与我的代码库无关之前,我不会讨论回到以前版本的代码有多少)。

IIS Express:(开发)

HTTP/2.0 200 OK
content-type: text/html; charset=utf-8
server: Kestrel
x-sourcefiles: [redacted]
x-powered-by: ASP.NET
date: Tue, 26 Mar 2019 23:05:06 GMT
X-Firefox-Spdy: h2

IIS:(暂存)

HTTP/1.1 200 OK
Transfer-Encoding: chunked
Content-Type: text/html; charset=utf-8
Server: Kestrel
Strict-Transport-Security: max-age=2592000
Date: Tue, 26 Mar 2019 23:04:47 GMT

调用 localhost 站点的结果是成功的,在 FireFox 的 devtools 中我可以看到已经返回了预期的数据,在这种情况下,与从 /Test 检索到的相同数据开始测试地点。

在登台站点上进行相同调用的结果会生成一个警报,其中包含预期的 html 文本。

我希望这两个环境产生相同的结果,即获取 html 文本。

有什么想法吗?我很困惑!

编辑 2019-03-28 我尝试从同一页面的上下文中对普通 XMLHttpRquest 执行相同操作并得到以下结果:

var x = new XMLHttpRequest();
undefined
x.open('GET', '/Test')
undefined
x.send(null)
undefined
x
XMLHttpRequest { onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, responseURL: "", status: 0, statusText: "", responseType: "",
response: "<h1>hi</h1>\r\n<script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-3.3.1.min.js\"></script>"

在对象的响应字段中可以清楚地看到来自 Web 服务器的预期响应。 (为清楚起见换行)

同理,直接作为浏览器开发工具中的图片:

编辑 2 2019-03-28

(除此之外,网络选项卡显示返回的数据正常)

因此,由于上次编辑似乎表明 jQuery 做了一些愚蠢的事情,我决定运行调试器并查看 jQuery 中发生了什么。在当前版本(3.3.1)中,我在第 9300 行中断,这是在请求完成之后并且在 jQuery 对其进行评估之后。我发现 done 函数的值似乎在我的本地 (dev) 和远程 (stg) Web 服务器之间有所不同:

本地

远程

主要问题是本地版本的 jQuery 使用 status = 0 触发 done(),而远程版本使用 status = 200 触发 done(),这是有道理的。

在这两个版本中,本地 response 变量的状态字段都是“成功”。在第 9247 行,jQuery 正在评估传递给 done() 的 status 变量,因为 0 没有传递,所以 isSuccess 设置为 false。

但是,网络显示:

我会继续挖掘,但会留意任何有见地的回应:)

编辑 3

所以done() 是从第 9538 行调用的:

callback = function( type ) {
                    return function() {
                        if ( callback ) {
                            callback = errorCallback = xhr.onload =
                                xhr.onerror = xhr.onabort = xhr.ontimeout =
                                    xhr.onreadystatechange = null;

                            if ( type === "abort" ) {
                                xhr.abort();
                            } else if ( type === "error" ) {

                                // Support: IE <=9 only
                                // On a manual native abort, IE9 throws
                                // errors on any property access that is not readyState
                                if ( typeof xhr.status !== "number" ) {
                                    complete( 0, "error" );
                                } else {
                                    complete(

                                        // File: protocol always yields status 0; see #8605, #14207
                                        xhr.status,
                                        xhr.statusText
                                    );
                                }

if ( typeof xhr.status !== "number" ) { 之前的行正在检查xhr.status,它是0,而不是实际的状态代码,尽管它肯定会返回 200。它解释了消息“错误”的来源!在done() 中,它正在检查状态码:

isSuccess = status &gt;= 200 &amp;&amp; status &lt; 300 || status === 304;

那么这个 0 是从哪里来的?!

编辑 4

最终问题似乎是XMLHttpRequest 给了我来自本地主机的状态 0,直到几天前才出现。超级沮丧:

var x = new XMLHttpRequest(); x.open('GET', 'https://localhost:44300/Test'); x.send(null);
undefined
x
XMLHttpRequest { onreadystatechange: null, readyState: 1, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, responseURL: "", 
status: 0, statusText: "", responseType: "", response: "" }

var x = new XMLHttpRequest(); x.open('GET', 'https://127.0.0.1:44300/Test'); x.send(null);
undefined
x
XMLHttpRequest { onreadystatechange: null, readyState: 1, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, responseURL: "", 
status: 0, statusText: "", responseType: "", response: "" }

编辑 5

因此,再次尝试将其缩减到最低限度,需要出错。我在 jquery 中扎根了一会儿,注意到 XHR 正在调用 JQ 的错误回调(分配给 xhr.onerror)所以我做了同样的 vanilla:

var x = new XMLHttpRequest()
XMLHttpRequest { onreadystatechange: null, readyState: 0, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, responseURL: "", status: 0, statusText: "", responseType: "", response: "" }

x.onerror = function () {console.log('error happened')};
function onerror()

x.open('GET','/Test')
undefined
x.send(null)
undefined
error happened
x
XMLHttpRequest { onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, responseURL: "", status: 0, statusText: "", responseType: "", response: "<h1>hi</h1>\r\n<script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-3.3.1.js\"></script>" }

这导致警报显示“发生错误”,所以我可以肯定地说,这不是 jQuery,而是一些奇怪的东西导致本地错误。

编辑 6

将上面的修改为x.onerror = function (e) {console.log('error happened'); console.log(e)}; 以吐出错误并得到这个:

error
  ​bubbles: false
  ​cancelBubble: false
  ​cancelable: false
  ​composed: false
  ​currentTarget: null
  ​defaultPrevented: false
  ​eventPhase: 0
  ​explicitOriginalTarget: XMLHttpRequest { readyState: 4, timeout: 0, withCredentials: false, … }
​  isTrusted: true
  ​lengthComputable: false
  ​loaded: 0
  ​originalTarget: XMLHttpRequest { readyState: 4, timeout: 0, withCredentials: false, … }
  ​returnValue: true
  ​srcElement: XMLHttpRequest { readyState: 4, timeout: 0, withCredentials: false, … }
  ​target: XMLHttpRequest { readyState: 4, timeout: 0, withCredentials: false, … }
  ​timeStamp: 594573
  ​total: 0
  type: "error"

这并不能说明很多问题。

编辑 7

将我的测试页面修改为更全面,以便我进行更好的测试:

<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script type="text/javascript">
    var x = new XMLHttpRequest();
    $(document).ready(function () {
        x.onerror = function (e) { console.log('error happened'); console.log(e); $('#err').text(e); };
        x.onreadystatechange = function () {
            if (x.readyState == 4) {
                $('#test').text(x.responseText);
            }
        };
        //x.open('GET', '/test.txt');
        x.open('GET', '/Search/Server?term=[redacted]');
        x.send(null);
    });
</script>
<h1>hi</h1>

<div style="border: 1px solid black">
    <pre id="test"></pre>
</div>

<div style="border: 1px solid red">
    <pre id="err"></pre>
</div>

当我要求 /test.txt 时,它工作正常,status = 200 没有错误

当我要求 /Test 这就是我在上面的代码 status = 0 时,产生了错误(没有关于原因的有用信息)

当我要求 /Search/Server?term=[redacted] 返回格式良好的 json 时,status = 0 产生错误(没有有用的信息)

AJAX 标头(工作)

HTTP/2.0 304 Not Modified
content-type: text/plain
last-modified: Thu, 28 Mar 2019 06:20:18 GMT
accept-ranges: bytes
etag: "1d4e52e505b3d27"
server: Kestrel
x-sourcefiles: [redacted]
x-powered-by: ASP.NET
date: Thu, 28 Mar 2019 06:47:09 GMT
X-Firefox-Spdy: h2

AJAX 标头(不工作)

HTTP/2.0 200 OK
content-type: text/html; charset=utf-8
server: Kestrel
x-sourcefiles: [redacted]
x-powered-by: ASP.NET
date: Thu, 28 Mar 2019 06:46:18 GMT
X-Firefox-Spdy: h2

HTTP/2.0 200 OK
content-type: application/json; charset=utf-8
server: Kestrel
x-sourcefiles: [redacted]
x-powered-by: ASP.NET
date: Thu, 28 Mar 2019 06:37:41 GMT
X-Firefox-Spdy: h2

可能是content-type 标头中的charset 吗?!

可能值得重申,所有这些使用 exact 相同代码的调用在生产/暂存中都可以正常工作 - 相同的浏览器,相同的身份验证(不是说它发生后相关),相同的相对 URL唯一的区别是 prd/stg 是 IIS 并且具有真正的证书,而本地是 IIS express 并且使用自签名但有异常。我能想到的。

【问题讨论】:

  • 这可能与CORS有关吗?当我在本地机器上弄乱与 CORS 相关的变量时,我也有同样的症状,即启用或禁用 Chrome CORS 扩展。
  • 我不这么认为。来源是一样的。当我执行相同的手动 ajax 请求并指定 FQDN(比如我的本地计算机上的暂存站点)时,我会收到相应的 CORS 错误:Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://[fqdn]:444/Test. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).[Learn More] 否则它在我提到的 3 个浏览器中的任何一个中都不会产生错误输出。
  • 所有这些浏览器都包含一个 Network 控制台,您可以在其中查看请求和响应。里面有提示吗?此外,在您的 error 处理程序中,您应该记录 c 的结果
  • 在我的编辑中,我添加了c 的值。 c 是一个空字符串。另外,我添加了 vanilla XHR,它显示数据恢复正常。即将添加另一个包含更多信息的编辑:)

标签: javascript jquery asp.net ajax


【解决方案1】:

事实证明,问题出在自定义 asp.net 中间件上,该中间件检查特定条件,然后允许管道继续。我假设它在开发中所做的任何事情都会导致请求中止或具有某些阻止它工作的质量。本质上问题代码是;

if (env.IsDevelopment())
{
    // Unimportant code here
    await _next(context);
    await Task.CompletedTask; // <<-- this line made it go wrong
}

用“return”替换问题行解决了问题。

if (env.IsDevelopment())
{
    // Unimportant code here
    await _next(context);
    return;
}

if 语句下还有更多工作,如果 IsDevelopment() == true 将被跳过但我相信我没有在此处的第一个块中正确终止此中间件。

为什么这会返回对XMLHttpRequest 的质量不同的响应,这超出了我的理解。我找不到任何指向不良反应的东西。

静态文件通过 AJAX 正常传输的事实表明,由于它是较早的中间件,因此问题可能是我的自定义中间件在管道中较晚出现。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-09
    • 1970-01-01
    • 1970-01-01
    • 2020-11-15
    • 2020-05-26
    • 1970-01-01
    相关资源
    最近更新 更多