On my frontend I am fetching a route on my express js proxy server. My frontend is receiving the response json data but the fetch request to the coingecko api doesnt appear to be using my api key even when I try and explicitly put it in the url or add it as a header.
If I click the direct url in my vscode it logs in the coingecko dev terminal as a request. But when I fetch it from my frontend it only appears to be calling without the api key included. Here is me explicitly putting in the api key instead of using headers it doesnt work with headers either.
express js proxy:
import express from "express";
import fetch from "node-fetch";
import cors from "cors";
const port = 3000;
const app = express();
app.use(cors());
app.get("/", async (req, res) => {
try {
// Call the fetchData function to fetch data from Coingecko
const data = await fetchData();
console.log("Data from Coingecko:", data);
res.json(data); // Send the fetched data as the response
} catch (error) {
console.error("Error:", error);
res.status(500).json({ error: "Internal Server Error" });
}
});
app.get("/fetch-data", async (req, res) => {
try {
// Call the fetchData function to fetch data from Coingecko
const data = await fetchData();
res.json(data); // Send the fetched data as the response
} catch (error) {
console.error("Error:", error);
res.status(500).json({ error: "Internal Server Error" });
}
});
app.listen(port, () => {
console.log(`Example app listening on port ${port}`);
});
// Define the fetchData function to fetch data from Coingecko
export const fetchData = async () => {
try {
console.log("Before fetch request");
const response = await fetch(
"https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&ids=bitcoin&x_cg_demo_api_key=********************"
);
const data = await response.json();
return data; // Return the data received from CoinGecko API
} catch (error) {
console.error("Error:", error);
throw new Error("Failed to fetch data from Coingecko API");
}
};
frontend javascript:
const button = document.getElementById("request");
const disp = document.getElementById("display");
const getBackEnd = async () => {
try {
const call = await fetch("http://localhost:3000/fetch-data");
if (call.ok) {
const jsonRes = await call.json();
return jsonRes;
}
} catch (error) {
console.log("error");
}
};
button.addEventListener("click", async () => {
// Make the event listener async
try {
const log = await getBackEnd(); // Await the function call
const string = JSON.stringify(log);
console.log(log);
disp.textContent = `response: ${string}`;
} catch (error) {
console.error("Error:", error);
}
});