#Can't use api in component.

4 messages · Page 1 of 1 (latest)

coral plaza
#

It says ERR_INVALID_URL

// /src/components/product.astro
const products1 = fetch('../pages/api/fetchproducts')
  .then(response => {
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    return response.json();
  })
  .then(data => console.log(data))
  .catch(error => console.error('Error fetching data:', error));

modern vaporBOT
#

Hi @coral plaza. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

In Astro, the fetch() function is used to make HTTP requests to APIs using the full URL. This means that you need to provide the full URL (e.g. <https://example.com/api>) or use Astro.url + "/api" if the API is on the same server.

In your case, you're trying to fetch data from a relative path ('../pages/api/fetchproducts'). This is likely causing the ERR_INVALID_URL error because fetch() expects a full URL.

Here's how you can modify your code:

// /src/components/product.astro
const products1 = fetch(Astro.url + '/api/fetchproducts')
  .then(response => {
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    return response.json();
  })
  .then(data => console.log(data))
  .catch(error => console.error('Error fetching data:', error));

In this code, Astro.url is used to get the base URL of your site, and '/api/fetchproducts' is the path to your API endpoint.

Remember, the fetch call will be executed at build time, and the data will be available to the component template for generating dynamic HTML. If you need to re-fetch data multiple times client-side, use a framework component (https://docs.astro.build/en/guides/framework-components/) or a client-side script (https://docs.astro.build/en/guides/client-side-scripts/) in an Astro component.

For more information, you can refer to the Astro documentation on data fetching (https://docs.astro.build/en/guides/data-fetching#fetch-in-astro).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@coral plaza kapa.ai is still learning and improving, please let us know how it did by reacting below