1

I have created a NodeJS server with Express and a frontend with Astro with SSR configured with the Astro adapter for NodeJS.

Now, I am trying to fetch data from the backend, and I don't know how to do it.

Here is the fetch request on the frontend:

---
let name = "Javi";

const handleContent = async () => {
  try {
    const response = await fetch("http://127.0.0.1:3000/api/astro/", {
      headers: {
        Accept: "application/json",
      },
    });
    console.log(await response.text());
    const data = await response.json();
    console.log(data);
    name = data.name;
    return data;
  } catch (error) {
    console.log(error);
  }
};
handleContent();
---

It does not find the endpoint for whatever reason and returns an error: Not found TypeError: Body is unusable at specConsumeBody (node:internal/deps/undici/undici:6539:15)

Here is my Express server:

import express from "express";
import { dirname, join } from "path";
import { fileURLToPath } from "url";
import cors from "cors";
import { handler as ssrHandler } from "./astro/dist/server/entry.mjs";

const PORT = process.env.PORT || 8001;
const app = express();
const __dirname = dirname(fileURLToPath(import.meta.url));

app.use(express.static(join(__dirname, "astro", "dist", "client")));
app.use(cors());
app.use(express.json());
app.use(ssrHandler);

app.get("/api/astro", (req, res) => {
  console.log("accessing api");
  res.json({ name: "Pepe" });
});

Any solution to fetch data from the backend while developing the app?

1 Answers1

0

i tried replicating this, it seems like you can't request twice with .text() and .json() on the response.

i did the same thing on data fetching using astro:

---
import Layout from "../../components/layouts/Layout.astro";

const res = await fetch('http://localhost:5243/api/v1/Test')

// these two is causing the errors.
console.log(await res.text())
const data = await res.json();

---

<Layout title="Test Page">
<p>{data.message}</p>
</Layout>

and when you try to remove (or comment i guess) the .text() or .json(), it will fetch the data fine now.

schierke
  • 1
  • 1