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.
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: