【发布时间】:2018-09-18 01:31:11
【问题描述】:
我正在尝试解析 JSON 文件,以便可以使用 JavaScript 访问其数据。这是 JSON 文件的示例:
"Veg": {
"French beans 300g": 81969,
"Bunched beetroot": 78272,
"Squash box": 45450,
"Bunched carrots 500g": 90435,
"Courgettes x3": 17824,
"Fennel x1": 14816,
"Shiitake mushrooms 150g": 5166,
"Spring onions 125g": 65034,
"Red peppers x2": 11671,
这是我正在使用的 JavaScript:
<script>
var sourceData;
// Initial data load
fetch("data.json", {
method: "GET",
headers: new Headers({
'Content-Type': 'application/json',
'Accept': 'application/json'
})
}).then(function (body) {
return body.json();
}).then(function (data) {
sourceData = data;
});
</script>
但我收到此错误:
Failed to load resource: Preflight response is not successful
和
Fetch API cannot load <file path> Preflight response is not successful
【问题讨论】:
-
您是如何发送请求的?我的意思是,您使用的是 cURL、Postman 还是浏览器?如果您使用的是浏览器,浏览器中的地址栏会显示什么?它是以
file:///还是http://开头的? -
你没有回答我的问题。
-
浏览器,文件:///
-
您不能使用从文件浏览器打开的浏览器窗口中的 XHR 请求(获取)。您的 HTML 文件必须从服务器打开才能正常工作。
-
我明白了。谢谢,我试试看
标签: javascript json cors fetch-api preflight