Chris
Chris

Reputation: 195

Can I create an XMLHttpRequest using a standard JavaScript function?

I would like to create a function which creates the structure of a desired XMLHttpRequest and outputs it as a variable that I can use. I have attempted this with the following code:

function prepareXMLHttpRequest(type) {
  var targetURL = 'http://localhost:3000/';

  var xhr = new XMLHttpRequest();
  xhr.open(type, targetURL, true);
  xhr.setRequestHeader('Content-Type', 'text/plain');
  //set any other options here
  return xhr;
}

My intention is to call that function with either GET or POST, and then send the result:

prepareXMLHttpRequest("GET").then(function(getRequest) {
    getRequest.send();
    // Do something here, for example console.log the output
  })

prepareXMLHttpRequest("POST").then(function(postRequest) {
    postRequest.send(outputString);
  })

When I try either of these statements, I receive the following error:

PrepareXMLHttpRequest(...).then is not a function

What am I doing wrong?

Upvotes: 1

Views: 49

Answers (2)

Rodrigo Leite
Rodrigo Leite

Reputation: 596

Another solution would be to use the fetch API. It's a more modern approach to XMLHttpRequest that uses promises by default.

fetch("https://myapi.com")
    .then(response => response.json())
    .then(data => console.log(data))

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API

Upvotes: 1

Teneff
Teneff

Reputation: 32158

What you're doing wrong is expecting the XMLHttpRequest to have a then property, but it does not. In order the result from your function to be thenable you need to return a promise like below

function prepareXMLHttpRequest(type) {
  var targetURL = 'http://localhost:3000/';
  return new Promise((resolve, reject) => {
  
    var xhr = new XMLHttpRequest();

    xhr.open(type, targetURL, true);
    xhr.setRequestHeader('Content-Type', 'text/plain');
    xhr.addEventListener('readystatechange', event => {
      event.readyState == 4 && event.status == 200 ? resolve(event) : reject(event)
    });
    xhr.send();
  })
}

Edit: the snippet above is just for illustration purposes for a good implementation that uses XMLHttpRequest() and returns Promise take a look at whatwg-fetch

Upvotes: 0

Related Questions