尝试从本地文件获取 json 数据并不断获取
"JSON.parse: unexpected end of data at line 1 column 1" .
我已经尝试了获取函数的许多参数,但我总是收到至少 1 个错误。
function getData() {
fetch('./data.json', {mode: 'no-cors'})
.then((res) => res.json())
.then((data) => {
console.log(data);
})
};
JSON 数据
{
"CustomerJohn": [
{
"month": "April",
"transaction": 1,
"price": 57
},
{
"month": "April",
"transaction": 2,
"price": 89
},
{
"month": "May",
"transaction": 1,
"price": 163
},
{
"month": "May",
"transaction": 2,
"price": 43
},
{
"month": "May",
"transaction": 3,
"price": 221
},
{
"month": "June",
"transaction": 1,
"price": 99
},
{
"month": "June",
"transaction": 2,
"price": 201
}
]
}
我想对数据进行 console.log 以确保其正常运行。
最佳答案
您将始终收到错误Fetch API 无法加载 file:///C:/your/path/to/data.json。不支持 URL 方案“file”。
如果您使用 fetch 检索未运行服务器的本地文件,即通过 file 访问
协议(protocol),而不是 JSON
文件:///http://
或 https://
。
为了访问它,您必须处于某个服务器环境中并且可以使用 XMLHttpRequest
来检索数据。我在下面为您准备了工作代码:
// Method which actually read json using XMLHttpRequest and promise
const jsonFileReader = async path => {
return new Promise((resolve, reject) => {
const request = new XMLHttpRequest();
request.open('GET', path, true);
request.responseType = 'blob';
request.onload = () => {
const reader = new FileReader();
reader.onload = e => resolve(e.target.result);
reader.onerror = err => reject(err);
reader.readAsDataURL(request.response);
};
request.send();
});
}
// This mthod will return the JSON
const returnJsonData = async (url) => {
const jsonData = await jsonFileReader(url);
console.log('Here is your JSON data: => ', jsonData);
return jsonData;
}
// Calling the function where you put URL
returnJsonData('./file.json');
此外,如果您不在服务器上运行此代码,您将收到以下错误,Access to XMLHttpRequest at 'file:///C:/your/path/to/data.json' from origin 'null' 已被 CORS 策略阻止:跨源请求仅支持以下协议(protocol)方案:http、data、chrome、chrome-extension、https。
原因还是协议(protocol)和跨源问题限制了您访问该文件。
因此,即使您的文件源自同一主机(localhost),但只要方案不同(http/file),它们就会被视为不同的来源。
<小时/>如何在 Node.js 中创建快速服务器
- 通过输入
npm install -g http-server
安装 http-server - 切换到
yoursome.html
所在的工作目录 - 通过发出
http-server -c-1
启动您的http服务器
这会运行 Node.js httpd
,它将目录中的文件作为静态文件提供,可从 http://localhost:8080
关于javascript - 尝试从本地文件获取 JSON 数据时出现语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58717906/