【发布时间】:2023-03-06 07:43:01
【问题描述】:
我一直在 JS 文件中使用 HTTP 请求从本地 JSON 文件中检索信息。它在我的 Firefox 和 Chrome 中的 Windows 计算机上运行良好,但是在 Mac 上运行时,Chrome 调试器会抛出一个错误,提示 Cross origin requests are only supported for HTTP...
我的HTTP请求代码如下:
var xhr = new XMLHttpRequest();
xhr.open("GET", "sample.json", true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
var status = xhr.status;
if ((status >= 200 && status < 300) || status === 305) {
var myData = JSON.parse(xhr.responseText);
window.myData = myData;
showAll(myData);
}
}
};
xhr.send(null);
有什么想法吗?谢谢
【问题讨论】:
-
是的,这是一个安全问题。您需要在服务器上运行它,并且此类请求不支持
file:///协议! -
@Lau — 当然不是。没有 HTTP 就无法发送 HTTP 标头。
-
“有什么想法吗?” — 安装 HTTP 服务器。
-
@Quentin 我的错,读得太快了
标签: javascript html json macos xmlhttprequest