Fetch vs Request

后端 未结 2 1839
忘了有多久
忘了有多久 2021-02-06 08:18

I\'m consuming a JSON stream and am trying to use fetch to consume it. The stream emits some data every few seconds. Using fetch to consume the stream gives me access to the dat

2条回答
  •  逝去的感伤
    2021-02-06 08:56

    Turns out I could get XHR to work - which doesn't really answer the request vs. fetch question. It took a few tries and the right ordering of operations to get it right. Here's the abstracted code. @jaromanda was right.

    var _tryXhr = function(target, data) {
      console.log(target, data);
      var xhr = new XMLHttpRequest();
    
      xhr.onreadystatechange = function () {
        console.log("state change.. state: "+ this.readyState);
        console.log(this.responseText);
        if (this.readyState === 4) {
          // gets hit on completion.
        }
        if (this.readyState === 3) {
           // gets hit on new event
        }
      };
    
      xhr.open("POST", target);
      xhr.setRequestHeader("cache-control", "no-cache");
      xhr.setRequestHeader("Content-Type", "application/json");
      xhr.send(data);   
    };
    

提交回复
热议问题