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?