Search code examples
javascriptxmlhttprequest

Should I check the status when doing HTTP POST or PUT requests with XHR?


This is a weird question I got after watching some videos about XHR and Async JS from an Udemy Course. There was a section where we create a simple library for making HTTP Requests in ES5. It started like this:

function EasyHTTP() {
  this.http = new XMLHttpRequest;
}

// Make an HTTP GET Request
EasyHTTP.prototype.get = function(url, callback) {
  this.http.open('GET', url, true);

  let self = this;
  this.http.onload = function() {
    if (self.http.status === 200) {
      callback(null, self.http.responseText)
    } else {
      callback('Error: ' + self.http.status)
    }
  }

  this.http.send();
}

I understood everything. But when the instructor was writing the post method, he did almost the same as in get method but said "We don't need to check the status, because we're doing a POST request" and the final method for POST ended up like this:

// Make an HTTP POST Request
EasyHTTP.prototype.post = function(url, data, callback) {
  this.http.open('POST', url, true);
  this.http.setRequestHeader('Content-type', 'application/json');

  let self = this;
  this.http.onload = function() {
    callback(null, self.http.responseText)
  }

  this.http.send(JSON.stringify(data));
}

And he did the same for the put method. But for the delete he checked the status like in the get method. I am confused, should we really "ignore" the status when doing POST and PUT requests? Why?


Solution

  • should we really "ignore" the status when doing POST and PUT requests?

    No, you should check for status code.

    All HTTP request methods, including POST and PUT, return a response indicating a failure or success, you should check the status and show to the user that their request was successful or it failed.