如何添加我创建并插入到获取 URL 中的本地 JSON 文件
useEffect(() => {
const fetchData = async () => {
try {
const res = await axios.get(`./custom`);
if (res.ok) {
console.log(res.data)
let data = res.data.products
setProductData(data)
}
// console.log(productData)
} catch (error) {
console.log(error)
}
}
fetchData()
}, [])
我期待来自本地 JSON 文件的数据 通过使用 fetch API 获取方法。
要在 fetch 请求中或与 axios 一起使用本地 JSON 文件,您只需指定文件的路径并处理数据。在 fetch 的情况下,您可以使用 JSON 文件的相对或绝对路径。
也就是说,服务器(如果使用)必须具有正确的配置才能提供静态文件,包括 JSON 文件。 (我不知道你有什么配置,但希望你已经设置好了) 那么,对于本地测试,您需要使用服务器,例如实时服务器或 IDE 中的内置服务器,因为浏览器可能会阻止通过 file:// 协议上传文件。
此代码加载 JSON 文件,处理数据,并将其设置为 ProductData 状态。
下面我会给出fetch和axios的例子。
Axios:
useEffect(() => {
const fetchData = async () => {
try {
const res = await axios.get(‘./custom.json’); // Specify the path to your JSON file
if (res.status === 200) {
const data = res.data;
console.log(data);
setProductData(data.products);
} else {
console.error(‘Error loading data:’, res.status);
}
} catch (error) {
console.error(‘Error while executing the query:’, error);
}
};
fetchData();
}, []);
获取:
再次,您可以在获取查询中使用相对路径或绝对路径。使用 Axios,该文件必须位于公共文件夹中才能在服务器上可用(但它有点变成公共的(有意义:)))。
useEffect(() => {
const fetchData = async () => {
try {
const res = await fetch(‘./custom.json’); // Specify the path to your JSON file
if (res.ok) {
const data = await res.json();
console.log(data);
setProductData(data.products);
} else {
console.error(‘Error loading data:’, res.status);
}
} catch (error) {
console.error(‘Error while executing the query:’, error);
}
};
fetchData();
}, []);
如果您发现我的解决方案有帮助,如果您用绿色标志将其标记为正确,我将不胜感激:)
祝你好运!