How to fetch data from your own server using Astro? – Astro

by
Ali Hasan
astro express node.js

Quick Fix: To fetch data from your own server in Astro, use the fetch() function. Avoid calling .text() and .json() on the response in the same request. Instead, use one of them to retrieve the data. Here’s an example using .json():

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

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

---

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

The Problem:

A developer has set up a NodeJS server with Express and a frontend with Astro, with SSR configured using the Astro adapter for NodeJS. When attempting to fetch data from the backend, the request fails with a "Not found" error and a "TypeError: Body is unusable" message. Despite defining an API endpoint on the Express server, the frontend code is unable to access it. The developer seeks a solution to successfully fetch data from the backend during development.

The Solutions:

Solution 1: Fetching Data from the Backend while developing an Astro app

To resolve the issue where your frontend is unable to fetch data from your backend, it’s recommended to avoid using both `.text()` and `.json()` on the same response object. Here’s a revised version of your frontend code:

---
let name = "Javi";

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

This code makes a GET request to the “/api/astro/” endpoint on your Express server, and it directly converts the response to a JavaScript object using `.json()`. You can now access the fetched data in your Astro component by using the `name` variable.

In your Express server code, ensure that the “/api/astro/” endpoint is properly defined and configured to return the desired data in JSON format. Here’s an example:

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

Q&A

When you try to fetch data using .text() and .json() this can cause an error what could you do?

Remove or comment out the second fetching method.

How can you fetch data from the backend while developing?

You can use the fetch method.

What is the issue with the following fetch request?

The issue is that .text() and .json() cannot be used together.

Video Explanation:

The following video, titled "Working with APIs in Astro is AMAZING! - YouTube", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

astro #webdevelopment Learn how to work with API data in Astro and also learn how to create your own API.