Reputation: 21
I'm using next.js and I want to fetch data from my data1.json file via getStaticProps(). The problem is that I get the error:
FetchError: invalid json response body at http://localhost:3000/data/data1.json reason: Unexpected token < in JSON at position 0
I have following code:
trainings.js (projectfolder/pages/trainings.js)
export default function Trainings({ data }) {
console.log(data);
return (
<main>
<h1>My trainings</h1>
</main>
);
}
export async function getServerSideProps() {
const res = await fetch('http://localhost:3000/data/data1.json');
const data = await res.json();
return { props: { data } };
}
data1.json (projectfolder/data/data1.json)
[
{
"name": "Jescie Duncan",
"email": "[email protected]",
"address": "Ap #666-9989 Nisi Avenue"
},
{
"name": "Karen Bartlett",
"email": "[email protected]",
"address": "P.O. Box 787, 2857 Tincidunt Ave"
},
{
"name": "Teegan Valdez",
"email": "[email protected]",
"address": "Ap #474-300 Nullam Avenue"
},
{
"name": "Stuart Silva",
"email": "[email protected]",
"address": "336-2367 Eu Ave"
}
]
Upvotes: 2
Views: 1830
Reputation: 62
I had the same problem, with this error:
Unexpected token < in JSON at position 0
There might be some hidden file/s included in your "data" folder. In my case it's .DS_Store
file. So what I did is,
"data" folder somewhere
"data" folder somewhere
and get all the JSON files by selecting it one-by-one, NOT doing the "Select All Files" because you might still pick the hidden files you are trying to get rid ofThis solved my problem every time it's happening. I'm pretty sure there are better ways to do it but I am surviving by doing this multiple times.
Upvotes: 0
Reputation: 572
Please check whether http://localhost:3000/data/data1.json
api is working or not. Because Nextjs support React components as default support in the pages folder not JSON. If you want serve as API you need to use NextJS api routes which you need to specifically put logic inside api
folder.
in api/data/data1.js
file
import data from '/path/to/json'
async function handler(req, res) {
return res.status(200).json(data)
}
export default handler;
But a better approach is:
As you have JSON file, you directly import that data in trainings.js
rather than calling an API.
import data from 'path/to/json';
export async function getServerSideProps() {
return { props: { data } };
}
Upvotes: 0