reactjs - axios 无法在 reactjs 中获取 public/[name].json 文件夹
问题描述
这是我的公共文件夹
public/
assets/
src/
items.json
index.html
src/
layout/
Items/ items.tsx - useEffect works fine
Overview/ Overview.tsx - useEffect does not work
index.tsx
package.json
这是我的 Overview.tsx
import React, { useEffect, useState } from 'react'
import axios from 'axios';
function Overview(props: any): JSX.Element {
const [items, setItems] = useState([])
useEffect(() => {
axios.get('items.json')
.then(res => setItems(res.data))
.catch(err => console.log(err))
}, []);
return (
<div>
//JSX Goes here
</div>
);
}
我的Overview.tsx与我的其他页面具有相同的代码,但这是我在开发工具中的 items.json 中得到的
标头
Request URL: http://localhost:3000/item/items.json
Request Method: GET
Status Code: 404 Not Found
Remote Address: 127.0.0.1:3000
Referrer Policy: no-referrer-when-downgrade
预览
Cannot GET /item/items.json
这是我的 Items.tsx在一个单独的文件夹中,这个块工作正常
const [items, setItems] = useState([])
useEffect(() => {
axios.get('items.json')
.then(res => setItems(res.data))
.catch(err => console.log(err))
}, []);
解决方案
只需将您的 axios 函数更改为:
axios.get('/items.json')
.then(res => setItems(res.data))
.catch(err => console.log(err))
因为你使用的是相对路径,它会从中获取,/currentPath/items.json
但是如果你使用/items.json
,axios 会从中获取你的 json 文件root/items.json