【问题标题】:xhr object does not have "withCredentials" property in Firefox and Chromexhr 对象在 Firefox 和 Chrome 中没有“withCredentials”属性
【发布时间】:2017-03-31 23:49:44
【问题描述】:

我想从客户端页面执行 CORS 请求。在enable-cors.org 中有一个表格,上面写着 Firefox(v 46. 和更高版本)和 Chrome(v 51. 和更高版本)都支持 CORS。 在html5rocks.com 中,他们说您可以通过检查创建的 XMLHttpRequest 对象是否具有“withCredentials”属性来检查浏览器是否支持 CORS(让我们暂时将 IE 排除在外)。所以我编写了一个非常简单的函数,它创建一个 xhr 对象并检查“withCredentials”属性并将结果加载到控制台上,然后我通过一个 html 按钮调用该函数,如下所示:

'use strict';

var corsPostRequest = function(){

    console.log("test");
    
    var xhr = new XMLHttpRequest();
    var lookInside = xhr.hasOwnProperty("withCredentials");
    console.log(lookInside);
    
    if (xhr.hasOwnProperty("withCredentials")) {
        console.log("we \'re good to go..");
    }
};// end of corsPostRequest
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <script src="javascripts/corsTest.js"></script>
</head>
<body>
    <button id="submit_entry" onclick="corsPostRequest()">POST</button>
</body>
</html>

我在控制台中得到的结果是:

测试

这意味着 xhr 对象没有“withCredentials”属性,因此无法使用 cors (?)。我已经在 Firefox (v 50.0) 和 Chrome (v 54.0.2840.71) 中尝试过这个,但我得到了相同的结果,尽管两种浏览器都应该这样做,至少根据我上面提到的链接。所以我想问:

1) 这可能是 Windows 10 浏览器(我正在运行的浏览器)的问题吗? 2)在这种情况下有什么办法可以做cors?

【问题讨论】:

  • 只分配它。所有现代浏览器都支持 cors。

标签: javascript google-chrome firefox cors


【解决方案1】:

xhr.hasOwnProperty("withCredentials")

你的错误是你假设它是一个自己的属性,而不是从原型继承的 getter/setter 对。

"withCredentials" in xhr // true

【讨论】:

  • 非常感谢。这个邪恶的 JSLint 建议我应该改用 hasOwnProperty,而我并没有注意这个问题。而且我认为我已经从 JSLint 中看到了足够多的东西......
猜你喜欢
  • 1970-01-01
  • 2012-04-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-10
  • 2022-07-17
  • 2015-04-30
  • 1970-01-01
相关资源
最近更新 更多