【发布时间】:2020-11-11 18:48:59
【问题描述】:
我从昨晚开始一直在编写我的 Javascript 代码,但是我似乎无法让它工作,它应该从我的 API 中提取访问,该 API 连接到我的 Lambda 函数和 DynamoDB。 它给了我以下错误:
(index):1 Access to fetch at 'api link here ' from origin 'origin here' 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.
我通过在 Google Chrome 上安装 CORS 移除程序解决了这个问题,但是它给了我这个错误:
VM37:4 Visitor Count:undefined
VM37:7 Uncaught (in promise) TypeError: Cannot set property 'innerHTML' of null
at <anonymous>:7:54
有谁知道如何修复这个错误并让我的 JS 从我的 API 链接中提取信息,我将不胜感激。 代码如下。
fetch('api link here')
.then(function(sitevisits)
{
console.log("Visitor Count:" +
sitevisits.visits);
document.querySelector("#Visitors-text").innerHTML = "Total Visitors"+
sitevisits.visits;
});
【问题讨论】:
-
"无法设置属性 'innerHTML' of null" 表示
document.querySelector("#Visitors-text")返回null。这意味着它找不到带有idVisitors-text的元素。这与从 API 中提取数据无关。 -
这是否意味着我必须使用 (DynamoDB) 中的主键作为 id?
-
不,它与数据库 ID 无关。它在 DOM 中搜索带有
id的元素。像<span id="Visitors-text"></span>这样的东西。如果找不到,它将返回null。 (但我假设你写了document.querySelector("#Visitors-text")这行?你期望它做什么?) -
关于 CORS 问题,您声明它是您的 API。那么为什么不添加适当的 CORS 标头呢? “在 Google Chrome 上安装 CORS 移除程序”只会降低您的 Chrome 的安全性。更不用说这不适用于使用您的应用程序的其他人。
-
好的,我会尝试重写我的代码,关于 CORS 我不知道该怎么做,这就是我提到它的原因。
标签: javascript amazon-web-services api