首页 > 解决方案 > 即使发送了响应,XMLHttpRequest 也只能达到 readystate 1

问题描述

我正在尝试向我在 app.js 中设置的节点服务器发送一个 httprequest。在 app.js 中定义了一个名为 allSnippets 的特定端点,当我运行http://localhost:3000/allSnippets时,它按预期工作,但是当我在 html 文件中创建一个应该向 app.js/allSnippets 发送 XMLHttpRequest 的按钮时,就绪状态永远不会超过 1。总的来说,我想达到就绪状态 4 并处理响应,但我选择更改“嗨”的颜色来测试我达到的就绪状态,因为我从未收到任何响应。此 html 文件位于名为“public”的目录中。包含“public”的目录也包含 app.js。

<p id = "text">Hi</p>
<button type = "button" onclick = "displaySnips()">View snippets</button>
<script>
  function displaySnips() {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function () {
      if (this.readyState == 2){
        document.getElementById("text").style.color = 'red';
      }
      else if (this.readyState == 1){
        document.getElementById("text").style.color = 'blue';
      }
      else if (this.readyState == 3){
        document.getElementById("text").style.color = 'green';
      }
      else if (this.readyState == 4 && this.status == 200) {
        document.getElementById("text").style.color = 'white';
      }
    }
    xhttp.open("GET", "../app.js/allSnippets", true);
    xhttp.send();
  }
</script>

关于为什么我没有达到就绪状态 4 的任何想法?

标签: javascriptxmlhttprequestxmlhttprequest-states

解决方案


推荐阅读