javascript - 获取对本地文件的请求不起作用

标签 javascript reactjs fetch-api

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

 // 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)
   })
 }

最佳答案

尝试像这样将您的 json 文件放在公用文件夹中:

公共(public)/电影.json

然后使用

获取
fetch('./movies.json')

fetch('movies.json')

我以前遇到过同样的问题。当我将 json 文件放在 public 文件夹中时,问题就解决了。 使用 fetch 时,React 通常会读取 public 文件夹中的 Assets /资源文件。

关于javascript - 获取对本地文件的请求不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50007055/

相关文章:

javascript - 嵌套有序列表

javascript - 将包含应用于 jQuery UI 可排序表可防止将高行移动到最后一个位置

javascript - react : Firing a custom alert from multiple components using an existing component having its own styles

javascript - 为什么 useReducer 的调度会导致重新渲染?

javascript - 链式 promise 并装饰对象

javascript - fetch的缓存需要客户端管理吗?

Javascript await/async - 这会导致竞争条件吗?

javascript - 尝试在 getElementId 无效的表单中注册后出现弹出窗口

reactjs - 初始化时跳过 Hook 更改 (useEffect)

javascript - 如何从提供 NET::ERR_CERT_AUTHORITY_INVALID 的站点获取数据