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 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) }) }
Fetch is an API to request data through networks using Http request, and we could also use this to request local files! Start Fetching Local Data!
POST request using fetch API: To do a POST request we need to specify additional parameters with the request such as method, headers, etc. In this example, we'll do a POST request on the same JSONPlaceholder and add a post in the posts. It'll then return the same post content with an ID.
Approach: First make the necessary JavaScript file, HTML file and CSS file. Then store the API URL in a variable (here api_url). Define a async function (here getapi()) and pass api_url in that function. Define a constant response and store the fetched data by await fetch() method.
You are trying to serve a static file with a fetch command, which inherently requires the file to be served by a server. To resolve the issue, you have a few options available to you. I am going to outline the two that are most commonly suggested for such a thing:
Finally, there are other options where you can upload one or more files online and fetch them from an external URL, however this might not be the optimal strategy.
Try to place your json file in the public folder like so :
public/movies.json
and then fetch using
fetch('./movies.json')
or
fetch('movies.json')
I have experienced the same problem previously. When I place the json file in the public folder, problem is solved. When using fetch, React normally reads asset/resources files in the public folder.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With