问题描述:使用 fetch 获取本地 JSON 文件时遇到了问题,无法正确获取文件并出现 Promise 相关的错误。
解决方案:
确认本地 JSON 文件路径和文件名是否正确。如果路径或文件名有误,会导致 fetch 找不到文件而出现错误。
确认本地 JSON 文件是否符合 JSON 格式。如果文件格式存在错误或乱码,也会导致 fetch 无法正确读取文件。
使用 async/await 或者 Promise 方法处理 fetch 返回的 Promise。在 fetch 请求中,需要使用 then 方法来处理 Promise 返回的数据。如果没有正确处理 Promise,会导致相关的错误。
参考代码:
// fetch 请求方法
fetch('data.json')
.then(response => {
return response.json();
})
.then(jsonData => {
console.log(jsonData);
})
.catch(error => {
console.error(error);
})
// async/await 请求方法
async function fetchData() {
try {
const response = await fetch('data.json');
const jsonData = await response.json();
console.log(jsonData);
} catch (error) {
console.error(error);
}
}
fetchData();