Reputation: 4659
I'm trying to make a fetch request to a local json file and I get this error saying Unhandled Rejection (SyntaxError): Unexpected token < in JSON at position 0
pointing at response.json()
. I tried adding proxy package.json but i get 500 internal error. How can I solve this?
componentDidMount() {
fetch('http://localhost:3000/items.json')
.then(function(response) {
if (response.status >= 400) {
throw new Error("Bad response");
}
return response.json();
})
.then(function(data) {
console.log(data)
});
}
json file:
[
{
data: [
{
name: "cnt",
level: "12"
},
{
name: "stewart",
level: "6"
},
{
name: "nic",
level: "7"
}
]
}
]
Upvotes: 2
Views: 2212
Reputation: 112927
If you are using Create React App then there is no other backend running that can serve your JSON file. Consider importing it with Webpack instead.
import data from './items.json';
class App extends React.Component {
componentDidMount() {
console.log(data);
}
// ...
}
Alternatively, you could put the file in the public
folder and you will be able to get it from the same origin.
class App extends React.Component {
componentDidMount() {
fetch("/items.json")
.then(response => {
if (!response.ok) {
throw new Error("Bad response");
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error(error));
}
// ...
}
Upvotes: 3