如何在页面上显示API信息

huangapple go评论58阅读模式
英文:

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&amp;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: &#39;GET&#39;,
	headers: {
		&#39;X-RapidAPI-Key&#39;: &#39;&lt;API-KEY&gt;&#39;,
		&#39;X-RapidAPI-Host&#39;: &#39;gamerpower.p.rapidapi.com&#39;
	}
};

fetch(&#39;https://gamerpower.p.rapidapi.com/api/giveaways?type=game&amp;sort-by=popularity&#39;, gamesList)
	.then(response =&gt; response.json())
	.then(data =&gt; console.log(data.gamesList))
		let games=data
		document.querySelector(&#39;h2&#39;).innerText=data.gamesList.title
	.catch(err =&gt; console.error(err));
&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;
	&lt;head&gt;
    	&lt;meta charset=&quot;utf-8&quot;&gt;
    	&lt;meta name=&quot;description&quot; content=&quot;This is where your description goes&quot;&gt;
    	&lt;meta name=&quot;keywords&quot; content=&quot;one, two, three&quot;&gt;

		&lt;title&gt;Game Giveaways&lt;/title&gt;

		&lt;!-- external CSS link --&gt;
		&lt;link rel=&quot;stylesheet&quot; href=&quot;css/normalize.css&quot;&gt;
		&lt;link rel=&quot;stylesheet&quot; href=&quot;css/style.css&quot;&gt;
	&lt;/head&gt;
	&lt;body&gt;

		&lt;h1&gt;Current Game Giveaways&lt;/h1&gt;
	
		&lt;button type=&quot;button&quot; name=&quot;button&quot;&gt;Get Burger&lt;/button&gt;

		&lt;h2&gt;Games&lt;/h2&gt;
		&lt;img src=&quot;&quot; alt=&quot;&quot;&gt;
		&lt;h3&gt;Description&lt;/h3&gt;

		
		

		&lt;script type=&quot;text/javascript&quot; src=&quot;js/main.js&quot;&gt;&lt;/script&gt;
	&lt;/body&gt;
&lt;/html&gt;

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,          // &#39;YYYY-MM-DD HH:mm:ss&#39; or &#39;N/A&#39;
  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,    // &#39;YYYY-MM-DD HH:mm:ss&#39; or &#39;N/A&#39;
  status: string,            // e.g. &#39;Active&#39;
  thumbnail: string,         // Resource URI
  title: string,
  type: string,              // e.g. &#39;Game&#39;
  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) =&gt; response.json()) // parse JSON response
  .then((data) =&gt; {
    // do stuff with data (in this case an object[])
  })
  .catch((err) =&gt; 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 = &#39;gamerpower.p.rapidapi.com&#39;;
const apiBaseUrl = `https://${apiHost}/api`
const apiKey = &#39;&lt;API-KEY&gt;&#39;;
const defaultRequestConfig = {
  method: &#39;GET&#39;,
  headers: {
    &#39;X-RapidAPI-Key&#39;: apiKey,
    &#39;X-RapidAPI-Host&#39;: apiHost
  }
};

const endpoint = `${apiBaseUrl}/giveaways?type=game&amp;sort-by=popularity`;
fetch(endpoint, defaultRequestConfig)
  .then(response =&gt; response.json())
  .then(gamesList =&gt; {
    const ul = document.createElement(&#39;UL&#39;);
    gamesList.forEach(({ title }) =&gt; {
      ul.append(Object.assign(document.createElement(&#39;LI&#39;), { innerText: title }));
    });
    document.querySelector(&#39;h2&#39;).after(ul);
  });

<!-- language: lang-html -->

&lt;link href=&quot;https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.1/normalize.min.css&quot; rel=&quot;stylesheet&quot;/&gt;
&lt;h1&gt;Current Game Giveaways&lt;/h1&gt;
&lt;button type=&quot;button&quot; name=&quot;button&quot;&gt;Get Burger&lt;/button&gt;
&lt;h2&gt;Games&lt;/h2&gt;
&lt;img src=&quot;&quot; alt=&quot;&quot;&gt;
&lt;h3&gt;Description&lt;/h3&gt;

<!-- end snippet -->

Here is the async/await version:

(async() =&gt; {
  const endpoint = `${apiBaseUrl}/giveaways?type=game&amp;sort-by=popularity`;
  const gamesList = await fetch(endpoint, defaultRequestConfig)
    .then(response =&gt; response.json());
  const ul = document.createElement(&#39;UL&#39;);
  gamesList.forEach(({ title }) =&gt; {
    ul.append(Object.assign(document.createElement(&#39;LI&#39;), { innerText: title }));
  });
  document.querySelector(&#39;h2&#39;).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(&#39;https://gamerpower.p.rapidapi.com/api/giveaways?type=game&amp;sort-by=popularity&#39;, gamesList)
  .then(response =&gt; response.json())
  .then(data =&gt; {
    console.log(data.gamesList);
    document.querySelector(&#39;h2&#39;).innerText = data.gamesList.title;
  })
  .catch(err =&gt; console.error(err));

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年2月18日 01:53:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/75487720.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定