【问题标题】:How do I embed an API call in my index.html file using JavaScript?如何使用 JavaScript 在我的 index.html 文件中嵌入 API 调用?
【发布时间】:2021-06-01 11:14:36
【问题描述】:

我正在尝试研究如何将 API 调用响应嵌入到我的 index.html 文件中,以便使用 JavaScript 更新网站计数器。

我尝试了多个博客和 YouTube 教程,但由于我对 JS 没有经验,我真的很挣扎。

这是我的 API: https://b9hsa93hif.execute-api.eu-west-2.amazonaws.com/Prod/hello/

这是我尝试的script.js 文件:

const countEl = document.getElementById('count');

updateVisitCount();

function updateVisitCount() {
    fetch('https://b9hsa93hif.execute-api.eu-west-2.amazonaws.com/Prod/hello/')
    .then(res => res.json())
    .then(res => {
        countEl.innerHTML = res.value;
    })
}

由于每次刷新页面时我的 API 都会自动更新,我认为我不需要 JavaScript 函数本身来计算 - 但我不知道如何正确重写它。

这是我尝试的index.html 文件中的 sn-p:

</div>  
  <p>This page was viewed</p>
  <h1 id="count"></h1>
  <p>times</p>

我希望我的静态网页显示This page was viewed [return result of API call] times

提前致谢!

--更新--

我已经设法解决了这个问题,感谢 @Barmar 的贡献,因为他们引导我朝着正确的方向前进,将 res.value 更新为 res.clicks 是必不可少的一步。

但是,主要问题是我的 API 链接到 API Gateway 和 Lambda 函数,而我在其中缺少一些关键代码。我在尝试在 API Gateway 资源上启用 CORS 时意识到了这一点,并在寻找帮助时发现了 this SO thread。其中的一个 cmets 有正确的代码可以包含在 Lambda 函数中(我在 >>>

return {
    'statusCode': 200,
    >>>'headers': {
        "Access-Control-Allow-Origin": "*"
    },<<<
    'body': json.dumps({'clicks': int(ddbResponse['Attributes']['clicks'])})

当我在我的 Lambda 函数中更新它并根据我更新的 index.html 文件刷新网站时,它工作正常。

再次感谢大家!

【问题讨论】:

  • 您是否在 JavaScript 控制台中遇到任何错误?喜欢与 CORS 相关的内容吗?
  • @Barmar 我正在使用 Codepen 并没有收到任何 CORS 错误,只是没有显示 API 响应
  • @AuqibRather 感谢您的建议,我不知道如何在我自己的用例中应用 JS,因为它包含 var price_USD = document.getElementById('price-usd');
  • res.value 应该是res.clicks

标签: javascript html aws-lambda aws-api-gateway


【解决方案1】:

您必须将代码更改为

fetch('https://b9hsa93hif.execute-api.eu-west-2.amazonaws.com/Prod/hello')
.then(response => response.json())
.then(res => {

// do something

document.getElementById("test").innerHTML = res.clicks;   //you used of clicks parameter

//do something

});
&lt;h1 id="test"&gt;&lt;/h1&gt;

【讨论】:

  • 感谢@mohammad soleimanpour。当我在 Codepen 中尝试时,我得到This page was viewed [blank] times。这正常吗?我是否必须实际上传新的 index.html 文件和 JavaScript 文件才能看到结果?
  • @fhoskyns 检查控制台。我收到错误Access to fetch at 'https://b9hsa93hif.execute-api.eu-west-2.amazonaws.com/Prod/hello' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
  • @Barmar,您使用的是哪个控制台?我什至不确定如何在控制台中检查它。对编码非常陌生
  • 在 Chrome 中使用 View -&gt; Developer -&gt; Javascript Console
  • @Barmar 我明白了 - 所以你认为我应该更改 AWS 中的 CORS 设置?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-11-16
  • 2016-08-31
  • 1970-01-01
  • 2023-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多