javascript - 新文本未显示

我制作了一个使用 API 的报价生成器网站。当我单击生成报价时,它只是停留在加载中 我该如何解决?

function randomQuote(){
    quoteBtn.classList.add("loading");
    quoteBtn.innerText = "Loading Quote...";
    fetch("http://api.quotable.io/random").then(response => response.json()).then(result => {
        quoteText.innerText = result.content;
        authorName.innerText = result.author;
        quoteBtn.classList.remove("loading");
        quoteBtn.innerText = "New Quote";
quoteBtn.addEventListener("click", randomQuote);
    });
}

我也收到这个错误,我不知道如何解决

index.js:12 Mixed Content: The page at 'https://mrquoter.netlify.app/' was loaded over HTTPS, but requested an insecure resource 'http://api.quotable.io/random'. This request has been blocked; the content must be served over HTTPS.

此外,当我在本地服务器上运行它时,它运行良好,但我将它托管在 netlify.app 上,它给出了一个错误

回答1

  1. 使用安全端点:https://api.quotable.io/random

  2. 也许使用 https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await 让您的代码更易于解析。

  3. 将按钮保留在要更新的元素之外。

const button = document.querySelector('button');
const quote = document.querySelector('.quote');

const endpoint = 'https://api.quotable.io/random';

button.addEventListener('click', handleClick, false);

async function handleClick() {
  const response = await fetch(endpoint);
  const data = await response.json();
  quote.textContent = data.content;
}
.quote { margin-top: 1em; }
<button>New quote</button>
<div class="quote"></div>

回答2

当您拥有 HTTPS 网站时,您不能混合从 HTTP 源加载资源,因为它会改变您的 HTTPS 网站的行为(即安全网站不再安全),这会在您的 HTTPS 网站上打开新的攻击媒介,如 https://developer.mozilla.org/en-US/docs/Web/Security/Mixed_content#mixed_active_content

回答3

您只需将查询 URL 更改为“https://api.quotable.io/random”,因为您的网站使用 HTTP,但您使用 HTTP 调用 API

HTTPs 是 HTTP 的安全版本

您可以在https://www.javatpoint.com/http-vs-https

找到更多关于 HTTP 和 HTTPS 的信息

相似文章

python - Python - 在多行和多列中比较 values

我是Python的新手,我有一个如下所示的数据框(请参阅原始数据table)。最终目标是协调来自2个系统(sys1与sys2,在“源”列中标记)的记录(即id、rg、prd和数量)。我如何使用1个函数...

随机推荐

最新文章