尝试使用异步和等待 运行 rapidapi 调用时出错
Getting an error trying to run rapidapi call using async and await
当我尝试 运行 来自 Rapid API
的 GET
请求时,我不断收到以下错误
Uncaught (in promise) ReferenceError: Cannot access 'getData' before initialization
const RAPIDAPI_KEY =
import.meta.env.VITE_RAPIDAPI_KEY;
const GEOLOCATION_URL = "https://ip-geo-location.p.rapidapi.com/ip/check?format=json";
const GEOLOCATION_HOST = "ip-geo-location.p.rapidapi.com";
const getData = async(url, host) => {
const response = await fetch(url, {
method: "GET",
headers: {
accept: "application/json",
"x-rapidapi-host": host,
"x-rapidapi-key": RAPIDAPI_KEY
}
})
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`)
}
return await response.json();
}
const runApiQueries = async() => {
// GET CITY NAME
const getData = await getData(GEOLOCATION_URL, GEOLOCATION_HOST);
console.log(getData);
}
runApiQueries();
问题出在线路上
const getData = await getData(GEOLOCATION_URL, GEOLOCATION_HOST);
应该是
const data = await getData(GEOLOCATION_URL, GEOLOCATION_HOST);
在任何情况下,您都不应该指定与函数或任何其他已定义标识符相同的变量名。
当我尝试 运行 来自 Rapid API
的GET
请求时,我不断收到以下错误
Uncaught (in promise) ReferenceError: Cannot access 'getData' before initialization
const RAPIDAPI_KEY =
import.meta.env.VITE_RAPIDAPI_KEY;
const GEOLOCATION_URL = "https://ip-geo-location.p.rapidapi.com/ip/check?format=json";
const GEOLOCATION_HOST = "ip-geo-location.p.rapidapi.com";
const getData = async(url, host) => {
const response = await fetch(url, {
method: "GET",
headers: {
accept: "application/json",
"x-rapidapi-host": host,
"x-rapidapi-key": RAPIDAPI_KEY
}
})
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`)
}
return await response.json();
}
const runApiQueries = async() => {
// GET CITY NAME
const getData = await getData(GEOLOCATION_URL, GEOLOCATION_HOST);
console.log(getData);
}
runApiQueries();
问题出在线路上
const getData = await getData(GEOLOCATION_URL, GEOLOCATION_HOST);
应该是
const data = await getData(GEOLOCATION_URL, GEOLOCATION_HOST);
在任何情况下,您都不应该指定与函数或任何其他已定义标识符相同的变量名。