尝试从本地文件中获取json数据并继续获取
"JSON.parse:第1列中数据的意外结束“。
对于fetch函数,我尝试了许多参数,但是我始终得到至少一个错误。
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的数据,以确保它是否正常运行。
发布于 2019-11-05 19:56:01
如果您使用fetch检索没有运行服务器的本地文件,即通过Fetch API cannot load file:///C:/your/path/to/data.json. URL scheme "file" is not supported.
协议访问JSON
文件,而不是通过http://
或https://
访问该文件,则始终会得到错误的file:///
文件。
为了访问它,您必须在某些服务器环境中,并且可以使用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' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
原因同样是,协议和跨源问题限制了您访问文件。
因此,即使您的文件来自同一个主机(localhost),但只要方案不同(http / file),它们就被视为不同的来源。
如何在Node.js中创建快速服务器
通过在工作目录中键入npm install -g http-server
yoursome.html
lives
http-server -c-1
启动http服务器。
这将运行一个Node.js httpd
,它将目录中的文件作为可从http://localhost:8080
访问的静态文件提供服务。
https://stackoverflow.com/questions/58717906
复制相似问题