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