I'm fetching data from /api/notes/1
and receive this:
{
"id":1,
"author":1,
"title":"Pierwsza notka",
"excerpt":"Taka tam notka, bla bla bla",
"body":"Pirwsza notka elo",
"private":1,
"created_at":"2021-04-07T12:59:59.000Z",
"updated_at":"2021-04-07T12:59:59.000Z"
}
Which is fine and dandy, but when I pass it into Next's getStaticProps
:
export async function getStaticProps({ params }) {
const res = await fetch(`${config.apiURL}/notes/${params.id}`);
const post = await res.json();
return { props: { post } };
}
It returns an error:
FetchError: invalid json response body at http://localhost:3000/api/notes/1 reason: Unexpected end of JSON input
What's going on here?
I'm fetching data from /api/notes/1
and receive this:
{
"id":1,
"author":1,
"title":"Pierwsza notka",
"excerpt":"Taka tam notka, bla bla bla",
"body":"Pirwsza notka elo",
"private":1,
"created_at":"2021-04-07T12:59:59.000Z",
"updated_at":"2021-04-07T12:59:59.000Z"
}
Which is fine and dandy, but when I pass it into Next's getStaticProps
:
export async function getStaticProps({ params }) {
const res = await fetch(`${config.apiURL}/notes/${params.id}`);
const post = await res.json();
return { props: { post } };
}
It returns an error:
FetchError: invalid json response body at http://localhost:3000/api/notes/1 reason: Unexpected end of JSON input
What's going on here?
Share Improve this question asked Apr 7, 2021 at 13:49 CholewkaCholewka 9833 gold badges10 silver badges29 bronze badges 4 |4 Answers
Reset to default 5The problem was my fault. The fetch returned 401 Unauthorized with no body.
For me, I got this error in Next 14.1 because I had an oversight and was trying to get a request body from a GET request:
export async function GET(request: Request) {
const body = await request.json();
}
Changing this to a post request fixed it for me:
export async function POST(request: Request) {
const body = await request.json();
}
Hope this helps someone
Ensure that the Status is 200 in your Network Tab. If its not (maybe 500) then you will have to check the URI you are fetching or that the server is responding...
Your Response res
from
const res = await fetch(`${config.apiURL}/notes/${params.id}`);
is empty or anything that cloud not be parsed into Json.
const post = await res.json();
toconst post = await res.text()
and console.logging post? – Johan Lindskogen Commented Apr 7, 2021 at 13:54res.text()
post
is just an empty string. What's strange, that the fetch goes smooth when running it in Chrome Devtools console. @Pointy @Chloe_Anderson Also, the request is not in Network tab. – Cholewka Commented Apr 7, 2021 at 14:01