javascript - xhr 对象在 Firefox 和 Chrome 中没有 "withCredentials"属性

标签 javascript google-chrome firefox cors

我想从客户端页面执行 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吗?

最佳答案

xhr.hasOwnProperty("withCredentials")

你在这里的错误是你假设它是一个自己的属性而不是从原型(prototype)继承的 getter/setter 对。

"withCredentials" in xhr // true

关于javascript - xhr 对象在 Firefox 和 Chrome 中没有 "withCredentials"属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40654858/

相关文章:

javascript - 服务器端的 AngularJS 变量

asp.net - session 变量被 Chrome 和 FF 击败

与 FF 和 IE 相比,jQuery 在 Chrome 中返回错误的元素位置

javascript - 如何在浏览器中更改 JavaScript,然后在修改后运行它?

asp.net - 在本地主机(Chrome 和 FF)上,过期时间少于 1 年时未设置 cookie

Javascript/jquery 适用于除 firefox 之外的所有浏览器

javascript - 更改 URL 字符串中的数据 - 使用 API 进行数据库请求

javascript skrollr 根据动态内容更新窗口高度

javascript - Safari 12 忽略 getUserMedia 约束

google-chrome - 在 Firefox 和 chrome 中以隐身模式或非隐私模式从浏览器的隐私模式打开书签