res.json() throwing error - SyntaxError: Unexpected non-whitespace
Answered
Spectacled bear posted this in #help-forum
Spectacled bearOP
Basically I copied the official guide and in my page.tsx file, I fetch an API like this:
And seems there's problem with JSON parsing when I run npm run build.
But after I change
async function getData() {
const res = await fetch("http://localhost:8080/ping");
// The return value is *not* serialized
// You can return Date, Map, Set, etc.
if (!res.ok) {
// This will activate the closest `error.js` Error Boundary
throw new Error("Failed to fetch data");
}
return res.json();
}
export default async function Home() {
const data = await getData()
console.log("Request sent!")
return (
<div>
<div>Hello World! I'm Home Page Start</div>
{data}
<div>I'm Home Page End.</div>
</div>
);
}And seems there's problem with JSON parsing when I run npm run build.
Error occurred prerendering page "/". Read more: https://nextjs.org/docs/messages/prerender-error
SyntaxError: Unexpected non-whitespace character after JSON at position 4 (line 1 column 5)
at JSON.parse (<anonymous>)
at parseJSONFromBytes (node:internal/deps/undici/undici:5419:19)
at successSteps (node:internal/deps/undici/undici:5390:27)
at fullyReadBody (node:internal/deps/undici/undici:1501:9)
at async specConsumeBody (node:internal/deps/undici/undici:5399:7)
But after I change
res.json() to res.json, it works.5 Replies
Spectacled bearOP
It may be a beginner's question but I completely have no clue :x
Can you show your API code?
app/ping/route.tsSpectacled bearOP
I don't have that configured, I'm trying to get from another backend written in JAVA
Spectacled bearOP
Thanks I fixed the problem by switching to Vue 🙂
Answer