【问题标题】:Javascript CORS blockedJavascript CORS 被阻止
【发布时间】: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 的元素。像&lt;span id="Visitors-text"&gt;&lt;/span&gt; 这样的东西。如果找不到,它将返回null。 (但我假设你写了document.querySelector("#Visitors-text")这行?你期望它做什么?)
  • 关于 CORS 问题,您声明它是您的 API。那么为什么不添加适当的 CORS 标头呢? “在 Google Chrome 上安装 CORS 移除程序”只会降低您的 Chrome 的安全性。更不用说这不适用于使用您的应用程序的其他人。
  • 好的,我会尝试重写我的代码,关于 CORS 我不知道该怎么做,这就是我提到它的原因。

标签: javascript amazon-web-services api


【解决方案1】:

您需要启用 CORS:

fetch(request, {mode: 'cors'});

那就这样做吧:

fetch('api link here', {mode: 'cors'})
   .then(function(sitevisits)
   {
   console.log("Visitor Count:" +
sitevisits.visits);

document.querySelector("#Visitors-text").innerHTML = "Total Visitors"+  
sitevisits.visits;   
 });

对于您的第二个错误,"#Visitors-text" 未找到,请检查具有此 id 的元素是否存在。

【讨论】:

  • 我尝试使用 {mode: 'cors} 并且它仍然给我相同的 cors 阻塞错误,至于我的第二个错误我在哪里检查元素是否存在?在 DynamoDB 中?
  • 在你前面的代码中,检查你的元素是否有 id #Visitors-text
  • HTML 中的前端代码对吗?对于所有这些问题,我很抱歉,我是编码新手。
  • 没问题,是的,你的 html,你尝试获取一个 id 为“Visitors-text”的元素,所以你需要一个

    或任何你想写文本的元素
  • 好的,修复了 null 错误,但是现在我的访客数显示:未定义。
猜你喜欢
  • 2018-12-30
  • 2019-08-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-11
  • 2021-04-16
  • 2015-10-09
  • 2018-10-18
相关资源
最近更新 更多