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

编程入门 行业动态 更新时间:2024-10-25 16:28:29
本文介绍了获取对本地文件的请求不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

I'm trying to make a request in a local file, but I don't know when I try to do on my computer show me an error. Is possible make a fetch to a file inside your project?

// 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 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('facebook.github.io/react-native/movies.json') .then( res => res.json() ) .then( (data) => { console.log(data) }) }

推荐答案

我遇到了同样的错误,我在代码中进行了两项更改以消除该错误.首先,您不需要快速服务器来为您的文件提供服务,您可以从 create-react-app 目录中公共文件夹内的本地 json 文件中读取数据.

I was encountering the same error and there are two changes I made in my code to get rid of the error. Firstly, you don't need an express server to serve your files you can read data from a local json file inside your public folder in your create-react-app directory.

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 函数中的路径参数如上所述是正确的.相对路径对我不起作用.其次,如图所示设置标题.从我的 fetch 调用中删除标题部分仍然给我这个错误.

First, as suggested in some of the answers above ensure that your json file is inside the public folder and the path parameter inside the fetch function is correct as above. Relative paths didn't work for me. Second, set the headers as shown. Removing the headers part from my fetch call was still giving me this error.

更多推荐

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

本文发布于:2023-10-30 03:32:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1541639.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:不起作用   本地文件

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!