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

这是我的概览。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

这是我的项目。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会从root/items.json中获取json文件

最新更新