英文:
How to display API information on a page
问题
抱歉,我无法执行代码。以下是您提供的代码的中文翻译:
const gamesList = {
method: 'GET',
headers: {
'X-RapidAPI-Key': '<API-KEY>',
'X-RapidAPI-Host': 'gamerpower.p.rapidapi.com'
}
};
fetch('https://gamerpower.p.rapidapi.com/api/giveaways?type=game&sort-by=popularity', gamesList)
.then(response => response.json())
.then(data => {
console.log(data.gamesList);
let games = data;
document.querySelector('h2').innerText = data.gamesList.title;
})
.catch(err => console.error(err));
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="description" content="This is where your description goes">
<meta name="keywords" content="one, two, three">
<title>Game Giveaways</title>
<!-- external CSS link -->
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<h1>Current Game Giveaways</h1>
<button type="button" name="button">Get Burger</button>
<h2>Games</h2>
<img src="" alt="">
<h3>Description</h3>
<script type="text/javascript" src="js/main.js"></script>
</body>
</html>
这段JavaScript代码似乎有一些问题。在.then
方法内部,您的代码有一些语法错误。在then
方法中,您需要对数据进行操作,但是您的操作被包含在大括号内,并且缺少一些必要的分号。此外,.catch
方法也应该在.then
链的末尾。这是一个修正后的版本:
const gamesList = {
method: 'GET',
headers: {
'X-RapidAPI-Key': '<API-KEY>',
'X-RapidAPI-Host': 'gamerpower.p.rapidapi.com'
}
};
fetch('https://gamerpower.p.rapidapi.com/api/giveaways?type=game&sort-by=popularity', gamesList)
.then(response => response.json())
.then(data => {
console.log(data.gamesList);
let games = data;
document.querySelector('h2').innerText = data.gamesList.title;
})
.catch(err => console.error(err));
希望这能帮助您解决问题!
英文:
I am working on creating a simple page that displays current free game giveaways using this API. https://gamerpower.p.rapidapi.com/api/giveaways?type=game&sort-by=popularity
However, I am still very new at working with APIs and am not sure if what I've been searching for is the right direction. The sources that I've been looking at haven't made much sense, and any examples I've tried to follow still result in an Uncaught Reference error telling me that the variable I am trying to use isn't defined.
Here is my very messy and basic code.
const gamesList = {
method: 'GET',
headers: {
'X-RapidAPI-Key': '<API-KEY>',
'X-RapidAPI-Host': 'gamerpower.p.rapidapi.com'
}
};
fetch('https://gamerpower.p.rapidapi.com/api/giveaways?type=game&sort-by=popularity', gamesList)
.then(response => response.json())
.then(data => console.log(data.gamesList))
let games=data
document.querySelector('h2').innerText=data.gamesList.title
.catch(err => console.error(err));
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="description" content="This is where your description goes">
<meta name="keywords" content="one, two, three">
<title>Game Giveaways</title>
<!-- external CSS link -->
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<h1>Current Game Giveaways</h1>
<button type="button" name="button">Get Burger</button>
<h2>Games</h2>
<img src="" alt="">
<h3>Description</h3>
<script type="text/javascript" src="js/main.js"></script>
</body>
</html>
I'm sure I am just missing something incredibly simple, but after working on it longer than I want to admit, I still can't wrap my head around where I'm going wrong.
答案1
得分: 1
以下是要翻译的内容:
Note: In the future, do not share your API key with anyone.
请注意:将来不要与任何人分享您的API密钥。
You need to understand the response from the API call. I will demonstrate this to you using TypeScript types.
您需要了解API调用的响应。我将使用TypeScript类型来演示这一点。
The response of the /api/giveaways
call is a Giveaway[]
("object array" or "array of objects").
/api/giveaways
调用的响应是一个 Giveaway[]
("对象数组" 或 "对象数组")。
Here is a Giveaway
object:
这是一个 Giveaway
对象:
interface Giveaway {
description: string,
end_date: string, // 'YYYY-MM-DD HH:mm:ss' or 'N/A'
gamerpower_url: string, // URL
id: number,
image: string, // Resource URI
instructions: string, // HTML
open_giveaway: string, // URL
open_giveaway_url: string, // URL
platforms: string, // CSV
published_date: string, // 'YYYY-MM-DD HH:mm:ss' or 'N/A'
status: string, // e.g. 'Active'
thumbnail: string, // Resource URI
title: string,
type: string, // e.g. 'Game'
users: number, // user count
worth: string // Currency in USD
}
Now that we understand the response of the API call, we know that we are dealing with an array of objects. Make sure that your second .then
call is a function that contains all your success logic.
现在我们了解了API调用的响应,我们知道我们正在处理一个对象数组。确保您的第二个.then
调用是一个包含所有成功逻辑的函数。
fetch(url, options)
.then((response) => response.json()) // parse JSON response
.then((data) => {
// do stuff with data (in this case an object[])
})
.catch((err) => console.error(err)); // handle errors
Here is a "working" demo. All you need to do is supply a valid API key.
这是一个“工作中”的演示。您只需要提供有效的API密钥。
const apiHost = 'gamerpower.p.rapidapi.com';
const apiBaseUrl = `https://${apiHost}/api`
const apiKey = '<API-KEY>';
const defaultRequestConfig = {
method: 'GET',
headers: {
'X-RapidAPI-Key': apiKey,
'X-RapidAPI-Host': apiHost
}
};
const endpoint = `${apiBaseUrl}/giveaways?type=game&sort-by=popularity`;
fetch(endpoint, defaultRequestConfig)
.then(response => response.json())
.then(gamesList => {
const ul = document.createElement('UL');
gamesList.forEach(({ title }) => {
ul.append(Object.assign(document.createElement('LI'), { innerText: title }));
});
document.querySelector('h2').after(ul);
});
Here is the async
/await
version:
以下是async
/await
版本:
(async() => {
const endpoint = `${apiBaseUrl}/giveaways?type=game&sort-by=popularity`;
const gamesList = await fetch(endpoint, defaultRequestConfig)
.then(response => response.json());
const ul = document.createElement('UL');
gamesList.forEach(({ title }) => {
ul.append(Object.assign(document.createElement('LI'), { innerText: title }));
});
document.querySelector('h2').after(ul);
})();
英文:
Note: In the future, do not share your API key with anyone.
You need to understand the response from the API call. I will demonstrate this to you using TypeScript types.
The response of the /api/giveaways
call is a Giveaway[]
("object array" or "array of objects").
Here is a Giveaway
object:
interface Giveaway {
description: string,
end_date: string, // 'YYYY-MM-DD HH:mm:ss' or 'N/A'
gamerpower_url: string, // URL
id: number,
image: string, // Resource URI
instructions: string, // HTML
open_giveaway: string, // URL
open_giveaway_url: string, // URL
platforms: string, // CSV
published_date: string, // 'YYYY-MM-DD HH:mm:ss' or 'N/A'
status: string, // e.g. 'Active'
thumbnail: string, // Resource URI
title: string,
type: string, // e.g. 'Game'
users: number, // user count
worth: string // Currency in USD
}
Now that we understand the response of the API call, we know that we are dealing with an array of objects. Make sure that your second .then
call is a function that contains all your success logic.
fetch(url, options)
.then((response) => response.json()) // parse JSON response
.then((data) => {
// do stuff with data (in this case an object[])
})
.catch((err) => console.error(err)); // handle errors
Here is a "working" demo. All you need to do is supply a valid API key.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const apiHost = 'gamerpower.p.rapidapi.com';
const apiBaseUrl = `https://${apiHost}/api`
const apiKey = '<API-KEY>';
const defaultRequestConfig = {
method: 'GET',
headers: {
'X-RapidAPI-Key': apiKey,
'X-RapidAPI-Host': apiHost
}
};
const endpoint = `${apiBaseUrl}/giveaways?type=game&sort-by=popularity`;
fetch(endpoint, defaultRequestConfig)
.then(response => response.json())
.then(gamesList => {
const ul = document.createElement('UL');
gamesList.forEach(({ title }) => {
ul.append(Object.assign(document.createElement('LI'), { innerText: title }));
});
document.querySelector('h2').after(ul);
});
<!-- language: lang-html -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.1/normalize.min.css" rel="stylesheet"/>
<h1>Current Game Giveaways</h1>
<button type="button" name="button">Get Burger</button>
<h2>Games</h2>
<img src="" alt="">
<h3>Description</h3>
<!-- end snippet -->
Here is the async
/await
version:
(async() => {
const endpoint = `${apiBaseUrl}/giveaways?type=game&sort-by=popularity`;
const gamesList = await fetch(endpoint, defaultRequestConfig)
.then(response => response.json());
const ul = document.createElement('UL');
gamesList.forEach(({ title }) => {
ul.append(Object.assign(document.createElement('LI'), { innerText: title }));
});
document.querySelector('h2').after(ul);
})();
答案2
得分: 0
使用data
的代码需要放在.then()
回调函数内。您在回调之后才使用了它。
fetch('https://gamerpower.p.rapidapi.com/api/giveaways?type=game&sort-by=popularity', gamesList)
.then(response => response.json())
.then(data => {
console.log(data.gamesList);
document.querySelector('h2').innerText = data.gamesList.title;
})
.catch(err => console.error(err));
英文:
The code that uses data
needs to be inside the .then()
callback. You have it after the callback.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
fetch('https://gamerpower.p.rapidapi.com/api/giveaways?type=game&sort-by=popularity', gamesList)
.then(response => response.json())
.then(data => {
console.log(data.gamesList);
document.querySelector('h2').innerText = data.gamesList.title;
})
.catch(err => console.error(err));
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论