在获取json文件时获得错误' NetworkError when trying to fetch resource '



我知道这个问题已经存在于堆栈溢出中,但它与我的问题无关。我没有找到解决办法。

我有两个文件index.htmldata.json

我代码:

<!doctype html>
<html>
<head>
</head>
<body>
<script>
async function fun(){
const res = await fetch('temp.json');
const dat = await res.json();
return      (Object.values(data));
}
console.log(fun());
</script>
</body>
</html>
{
"1": "One",
"2": "two",
"3": "Three"
}

我得到了标题中提到的错误在我的浏览器(firefox和移动chrome)。控制台:

Promise { <state>: "rejected", <reason>: TypeError }
<state>: "rejected"
<reason>: TypeError: NetworkError when attempting to fetch resource.
<prototype>: Promise.prototype { … }
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at file:///home/kashyap/Desktop/data.json. (Reason: CORS request not http).

正如@chrwahl在评论中提到的,我们需要使用web服务器而不是文件系统来解决这个问题。由于安全原因,firefox不允许这样做(不确定其他浏览器是否如此)。

我已经将文件移动到我的web服务器(apache)的根文件夹(linux中的/var/www/html/和Xamp中的htdocs文件夹)。

错误已消失,承诺已实现。

最新更新