#Fetch works in component file, but not in /page/api route

8 messages · Page 1 of 1 (latest)

unkempt smelt
#

I'm new to NextJS and this may be an issue with running 13.3.4 and me not understanding some nuances. But in my <Home /> component, I'm able to fetch data from a FastApi server successfully. But when I move the call to /page/api/chat/ the error response I get is an HTML page back. Specifically expected token '<', "<!DOCTYPE "... is not valid JSON. What am I missing about making external api calls?

Works:

async function handleSubmit() {
    const response = await fetch("http://localhost:8006/chat", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ question: userInput }),
    });

    const data = await response.json();
    if (data.error) {
      setResponse(data.error);
    } else {
      setResponse(data.answer);
    }
  }```

**Doesn't work:** `/pages/index`

async function handleSubmit() {
const response = await fetch("/api/chat", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ question: userInput }),
});
... rest of code```

/pages/api/chat

export default async function handler(req, res) {
  const response = await fetch("http://localhost:8006/chat", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ question: req.body.question }),
  });

  const data = await response.json();

  if (data.error) {
    console.log(data, "data");
  } else {
    res.status(200).json({ answer: data.answer });
  }
}
onyx talon
#

Can you try with 127.0.0.1 instead of localhost?

unkempt smelt
#

that worked! thank you @onyx talon . curious if that's a Next thing or I should just be using 127.0.0.1 for localhost whenever working with apis

onyx talon
#

The reason for that is most likely Node.js

#

If you're using Node 17+, it uses your system's config for the preferred IP when fetching from localhost

#

This is usually your IPv6

#

But since your server is not running on v6, but on v4, it is not reachable.

unkempt smelt
#

great to know. thanks for the education