K
K
Kirill2021-02-02 19:29:09
JavaScript
Kirill, 2021-02-02 19:29:09

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}
  }
}


I get such an error

60197c5919221871966725.jpeg


json file something like this:

{
      "elements": [
        {
          "name": "Доставка",
          "url": ""
        },
        {
          "name": "Оплата",
          "url": ""
        },
        {
          "name": "Возврат",
          "url": ""
        }
      ],
      "title": "Покупателям"
    }


What is the problem and how to get the data correctly?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
K
Kirill, 2021-02-02
@Lirrr

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)
}

The request itself:
export async function getServerSideProps() {
  const res = await fetch(`http://localhost:3000/api/product`)
  const data = await res.json()
  return {
    props: {product} 
  }
}

And everything worked.
Thanks to all. Another example that you need to read the documentation, and not get stupid questions from smart people.

N
Nadim Zakirov, 2021-02-02
@zkrvndm

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.

V
Vasily Bannikov, 2021-02-02
@vabka

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.

A
Alexander Cheremkhin, 2021-02-02
@Che603000

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 question

Ask a Question

731 491 924 answers to any question