【问题标题】:Rapidapi Api request with XMLHttpRequest使用 XMLHttpRequest 的 Rapidapi Api 请求
【发布时间】:2020-05-23 23:54:15
【问题描述】:

这是我的第二篇文章,希望比上次更幸运,最后得到一些回复。 ????

我正在尝试使用javascript“XMLHttpRequest”制作一个Rapidapi api请求 我必须说该 api 与 ios siri 快捷方式完美配合。

这是 apirapit 网站在“XMLHttpRequest”部分提供的代码:

var data = null;

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;

xhr.addEventListener("readystatechange", function () {
    if (this.readyState === this.DONE) {
        console.log(this.responseText);
    }
});

xhr.open("GET", "https://download-video-youtube1.p.rapidapi.com/mp3/medPORJ8KO0");
xhr.setRequestHeader("x-rapidapi-host", "download-video-youtube1.p.rapidapi.com");
xhr.setRequestHeader("x-rapidapi-key", "[my key here]");

xhr.send(data);

这是我的代码:

    <!DOCTYPE html>
<html>
<body>

<h2>The XMLHttpRequest Object</h2>

<button type="button" onclick="loadDoc()">Request data</button>

<p id="demo"></p>

<script>
function loadDoc() {
  var xhttp = new XMLHttpRequest();
xhttp.withCredentials = true;
url='https://download-video-youtube1.p.rapidapi.com/mp3/xF5t2jOsCt8';
  xhttp.onreadystatechange = function() {
    if ((this.readyState == 4 && this.status == 200 )||(this.readyState === this.DONE)) {
      document.getElementById("demo").innerHTML = "ciao" + this.responseText;
    }
  };
  xhttp.open("GET", url);
xhttp.setRequestHeader("x-rapidapi-host", "download-video-youtube1.p.rapidapi.com");
xhttp.setRequestHeader("x-rapidapi-key", "[my key here]");
  xhttp.send();
}
</script>

</body>
</html>

为了测试,我创建了一个简单的银行 html 页面,以便在按下按钮后在按钮下方显示 JSON 响应。结果就是我在 this.responseText 之前设置的字符串“ciao”。如果我删除 apikey 或使用错误值修改它,则会出现 JSON 错误消息(就像发布的案例一样,因为我故意删除了它)。 否则如所说,但“ciao”字符串

有语法错误吗?它的行为有这样的逻辑原因吗?

谢谢 佛朗哥

【问题讨论】:

    标签: javascript html xmlhttprequest rapidapi


    【解决方案1】:

    尝试将data 变量添加为null。这就是 RapidAPI 在他们的代码 sn-p 中提供的。

    function loadDoc() {
      const data = null
      var xhttp = new XMLHttpRequest();
      xhttp.withCredentials = true;
      url='https://download-video-youtube1.p.rapidapi.com/mp3/xF5t2jOsCt8';
      xhttp.onreadystatechange = function() {
        if ((this.readyState == 4 && this.status == 200 )||(this.readyState === this.DONE)) {
          document.getElementById("demo").innerHTML = "ciao" + this.responseText;
        }
      };
      xhttp.open("GET", URL);
      xhttp.setRequestHeader("x-rapidapi-host", "download-video-youtube1.p.rapidapi.com");
      xhttp.setRequestHeader("x-rapidapi-key", "my key here");
      xhttp.send(data);
    }
    

    【讨论】:

      猜你喜欢
      • 2013-05-05
      • 1970-01-01
      • 2018-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-26
      • 2015-07-25
      相关资源
      最近更新 更多