在我的前端,我正在我的 Express JS 代理服务器上获取路由。我的前端正在接收响应 json 数据,但对 coingecko api 的获取请求似乎并未使用我的 api 密钥,即使我尝试将其显式放入 url 中或将其添加为标头。
如果我单击 vscode 中的直接 url,它会作为请求登录到 coingecko 开发终端。但是当我从前端获取它时,它似乎只是在不包含 api 密钥的情况下进行调用。这是我明确输入 api 密钥而不是使用标头,它也不适用于标头。
express js 代理:
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");
}
};
前端 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);
}
});
最好将 API 密钥包含在请求标头中,而不是包含在 URL 本身中,特别是如果它是秘密 API 密钥。
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",
{
headers: {
'x-cg-demo-api-key': 'YOUR_API_KEY'
}
}
);
const data = await response.json();
return data;
} catch (error) {
console.error("Error:", error);
throw new Error("Failed to fetch data from Coingecko API");
}
};