How to Fetch Data from Your Own Server Using Astro?
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...
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("", {
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 Answer
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(')
// 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.