【问题标题】:CORS issue with POST, inconsistent behaviour in ChromePOST的CORS问题,Chrome中的行为不一致
【发布时间】:2015-09-01 02:37:15
【问题描述】:

来自http://localhost:8080的JavaScript请求:

function sendMessage() {
   var params =
        'AppKey=' + config.appKey +
        '&MetadataJson=' + encodeURIComponent(config.metadataJson),
       url = 'http://localhost/Controller/Action',
       xhr = new XMLHttpRequest();

    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
            alert('hit!');
        }
    }

    xhr.open('POST', url, true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.withCredentials = true;
    xhr.send(params);
}

转换为 HTTP 请求:

POST http://localhost//Controller/Action HTTP/1.1
Host: localhost
Connection: keep-alive
Content-Length: 667
Origin: http://localhost:8080
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.155 Safari/537.36
Content-Type: application/x-www-form-urlencoded
Accept: */*
Referer: http://localhost:8080/index.html
Accept-Encoding: gzip, deflate
Accept-Language: en-GB,en-US;q=0.8,en;q=0.6
Cookie: ASP.NET_SessionId=aoqjuh2xob20qt5jpe2jo01i

AppKey=...

HTTP 响应:

HTTP/1.1 200 OK
Cache-Control: private
Server: Microsoft-IIS/8.5
Access-Control-Allow-Origin: http://localhost:8080
Access-Control-Allow-Credentials: true
X-AspNetMvc-Version: 5.2
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Wed, 19 Aug 2015 06:17:02 GMT
Content-Length: 0

但是:浏览器 (Chrome) 中的行为不一致。有时alert('hit!') 会按预期调用,但通常是在readyState 等于4、status 等于0 时。

这看起来像是一个 CORS 问题。对我来说,请求中与 CORS 相关的唯一标头字段似乎是 Origin 并且服务器响应 Access-Control-Allow-Origin 具有相同的值,所以从 CORS 的角度来看一切都应该没问题?

关于如何更改 JavaScript 或服务器实现 (ASP.NET MVC) 的任何建议?

更新:

相关的HTML:

<li class="my-link">
    <a href="">Get Help</a>
</li>

... 以及将 HTML 连接到 sendMessage() 的 JavaScript:

window.onload = function () {
    var els = document.getElementsByClassName('my-link'), i;

    for (i = 0; i < els.length; i += 1) {
        els[i].onclick = sendMessage;
    }
}

【问题讨论】:

  • This looks like a CORS issue. - 为什么? but usually, at the point when readyState equals 4, status equals 0. - 你是说 alert(hit) DOES 在 readyState === 4 和 status === 0 时被调用?
  • @JaromandaX:状态有时等于 0,有时等于 200。后者是预期的,然后 alert() 被调用。状态 0 是浏览器由于跨域问题拒绝将结果传递给 JavaScript 的典型结果。

标签: javascript asp.net-mvc cors


【解决方案1】:

在我原来的描述中看不到实际问题。似乎可行的解决方案是将sendMessage() 修改为返回false

function sendMessage() {
    ...
    xhr.send(params);

    return false;
}

知道为什么需要这样做会很有趣。我通过研究页面重定向(分配window.location.href)失败的案例找到了解决方案,建议的解决方案是将return false添加到相关的表单提交中。这甚至不是表单提交...

【讨论】:

    猜你喜欢
    • 2013-08-22
    • 1970-01-01
    • 2021-03-05
    • 2015-08-20
    • 1970-01-01
    • 2019-08-18
    • 2021-08-22
    • 1970-01-01
    • 2020-01-15
    相关资源
    最近更新 更多