我正试图在本地文件中发出请求,但我不知道何时try 在我的计算机上显示错误.是否可以提取项目中的文件?

 // Option 1
 componentDidMount() {
     fetch('./movies.json')
     .then(res => res.json())
     .then((data) => {
        console.log(data)
     });
 }

 error: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 at App.js: 10 -->  .then(res => res.json())

 // Option 2
 componentDidMount() {
    fetch('./movies.json', {
       headers : { 
         'Content-Type': 'application/json',
         'Accept': 'application/json'
       }
    })
   .then( res => res.json())
   .then((data) => {
        console.log(data);
   });
 }

 error1: GET http://localhost:3000/movies.json 404 (Not Found) at App.js:15 --> fetch('./movies.json', {
 error2: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 at App.js: 10 -->  .then(res => res.json())


 // This works
 componentDidMount() {
   fetch('https://facebook.github.io/react-native/movies.json')
   .then( res => res.json() )
   .then( (data) => {
      console.log(data)
   })
 }

推荐答案

我遇到了同样的错误,我在代码中做了两个更改来消除这个错误.首先,你不需要一台express服务器来为你的文件提供服务,你可以从你的create react应用目录下的公用文件夹中的本地json文件中读取数据.

  const getData=()=>{
     fetch('data.json',{
          headers : { 
            'Content-Type': 'application/json',
            'Accept': 'application/json'
           }
         }
        )
         .then(function(response){
            console.log(response)
            return response.json();
          })
           .then(function(myJson) {
              console.log(myJson);
            });
      }
      useEffect(()=>{
        getData()
      },[])

首先,正如上面的一些答案所建议的,确保json文件位于公用文件夹中,并且fetch函数中的path参数如上所述是正确的.相对路径对我不起作用.

Reactjs相关问答推荐

react 导致不必要的回归

react-hook-form问题:为什么getValues不返回大多数当前值?

如何使用json将购物车数组传递到后台API

如何实现黑暗模式 map ?

有正确的方法来设置我的金牛座应用程序的图标吗?

为什么VScode中的React应用程序无法识别文件夹 struct ?

props 可以在Reaction中锻造吗?

For循环中的元素在Reaction中丢失挂钩

try 在Dockerfile中使用AWS CLI将React构建工件上传到S3时出错

REACTJS:在Reaction中根据路由路径更改加载器API URL

React中的useEffect钩子

在新屏幕上显示照片时出现问题-react

为什么我得不到我想要的数据?

透明MOV文件未出现在我的React网页中

React redux 工具包 useGetFilterProductsQuery 和 useGetFilterProductsByCategoriesQuery 未定义为函数

如何更新 FunctionComponentElement 的 props

如何使用服务器中的数据自动填充表单字段?

在 React-Select 中显示多值的倒序

使用 useRef(uuid()) 的目的是什么?

在react 路由dom版本6中的组件内添加路由