I am using getStaticProps and getStaticPaths, I used fetch API to call an API endpoint (which is Wordpress headless CMS in my case) and set the paths for dynamic routing. When I run npm dev it works fine, the data is fetched correctly. But at build time it gives error that:
FetchError: invalid json response body at https://abr.af/wp/wp-json/wp/v2/advisors reason: Unexpected token < in JSON at position 0
My code in pages/advisor/[advisor].js
export const getStaticPaths = async () => {
const advisors = await getAdvisors()
const paths = advisors.map((each) => {
return {
params: { advisor: each.slug },
}
})
return {
paths,
fallback: false,
}
}
export const getStaticProps = async ({ params }) => {
const query = params.advisor
const advisors = await getAdvisors()
const advisor = advisors.find((advisor) => advisor.slug === query)
return {
props: {
advisor,
},
}
}
my fetch function in component/FetchData.js
export async function getAdvisors() {
const res = await fetch('https://abr.af/wp/wp-json/wp/v2/advisors', {
method: 'GET',
headers: {
// update with your user-agent
'User-Agent': '*',
Accept: 'application/json; charset=UTF-8',
},
})
const advisors = await res.json()
return advisors
}
export async function getExpertise() {
const res = await fetch('https://abr.af/wp/wp-json/wp/v2/expertise', {
method: 'GET',
headers: {
// update with your user-agent
'User-Agent': '*',
Accept: 'application/json; charset=UTF-8',
},
})
const expertise = await res.json()
return expertise
}
I googled this issue and find that I should add User-Agent header to my request but this not solve my problem.
I am new to Next.js, I don't know what is the reason any help would be appreciated.