Answer the question
In order to leave comments, you need to log in
Why can't fetch data from localhost?
There is a project on nextjs, I want to receive data for pages through a fetch request to a local json / js file.
Request code in the page component:
export async function getServerSideProps(context) {
const res = await fetch(`http://localhost:3000/api/product`)
const json = await res.json();
console.log('json', json)
return {
props: {data}
}
}
{
"elements": [
{
"name": "Доставка",
"url": ""
},
{
"name": "Оплата",
"url": ""
},
{
"name": "Возврат",
"url": ""
}
],
"title": "Покупателям"
}
Answer the question
In order to leave comments, you need to log in
managed to solve. First I corrected the path, 404 disappeared, but the output in the html console remained. In the next js documentation, I found an example of using the rest router api, there, after the data object, there was such an entry:
export default function handler(req, res) {
res.status(200).json(product)
}
export async function getServerSideProps() {
const res = await fetch(`http://localhost:3000/api/product`)
const data = await res.json()
return {
props: {product}
}
}
Obviously you have crooked JSON. It looks like you are trying to parse not JSON, but a JavaScript record of an object. Try using eval() to read the object.
Apparently, in fact, it’s not json that comes in the response, but html, as evidenced by the presence <
Maybe the server redirects to some login page there, whether a similar error occurs there.
First you need to process the error.
No one knows what your server is responding to.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question