Reputation: 9790
I am experiencing some unexpected behavior using react
and fetch
. It should be very straight forward.
My code looks like the following:
import React, { Component } from 'react';
class App extends Component {
componentDidMount() {
fetch('/dict.json')
.then(res => res.json())
.then(json => console.log(json))
}
render() {
return (
<p>Example</p>
);
}
}
and my folder structure looks like this
- src
|_app.js
|_dict.json
- index.html
When I check the network it is requesting the index.html
page which makes no sense to me. Has anyone experienced this before?
Upvotes: 1
Views: 9276
Reputation: 21
Try this file structure
- public |_index.html |_dict.json - src |_app.js
Upvotes: 1
Reputation: 3977
Production: If this code is going to run in production then fetch
is not going to work here unless you have setup a web server to serve that JSON file, however, you could import the local JSON file instead:
import dict from './_dict.json';
Then inside of your componentDidMount
you can just map over it
let results = dict.map((item, index) => {
// ...
});
Localhost: If you just want to run this on localhost, then I don't see why it wouldn't work unless, and which I suspect is the case, your React app is proxying HTTP requests to a local webserver (as is extremely common in Reactjs development) and that local webserver is not setup to serve your JSON file up. So check your package.json or webpack setup for something like this:
"proxy": "http://localhost:8080"
And configure the webserver running on that port to serve your JSON file up in response to a request.
Upvotes: 3