3

In an attempt to get rid of Ajax calls I have changed my code to use the Javascript Fetch API which is very clean.

In the example below, I had to comment out the body fetch option of the request as well as change the method option to GET.

I did this to see if it would work and.. it did.

Now I am wondering how am I going to pass the body fetch option params to the request.

Lastly, I have run into something called AbortController Interface and would like to know if you can show me how to implement it in this sample below or if it cannot benefit from it at all.

Thank you

// POST DATA
function postData(url = 'https://api.myjson.com/bins/elr1f', params = [{param1Key: 'param1Val'}]) {

  const fetchOptions = {
                    method: 'GET', // *GET, POST, PUT, DELETE, etc.
                    mode: 'cors', // no-cors, cors, *same-origin
                    cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
                    credentials: 'same-origin', // include, *same-origin, omit
                    headers: {
                      // 'Content-Type': 'application/x-www-form-urlencoded',
                      'Content-Type': 'application/json',
                      // 'Content-Type', 'text/xml'
                    },
                    redirect: 'follow', // manual, *follow, error
                    referrer: 'no-referrer', // no-referrer, *client
                    // body:     JSON.stringify(params), // body data type must match "Content-Type" header
                };

  // Default fetchOptions are marked with *
    return fetch(url, fetchOptions)

    .then(function(response) {

      // RESPONSE VALIDATION
      switch (response.status) {
        case 200:
          // code...
          console.info('HTTP response status: 200 OK');
          return response;
          break;

        case 404:
          // code...
          throw new Error('HTTP response status: 404 Not Found.');
          break;

        case 500:
          // code...
          throw new Error('HTTP response status: 500 Internal Server Error.');
          break;

        case 503:
          // code...
          throw new Error('HTTP response status: 503 Service Unavailable.');
          break;
        
        default:
          // code...
          break;
      }
    
    })

    // parse JSON response into native JavaScript object(s) 
    .then (response => response.json() )
    // access the node we want
    .then (response => console.info(response.users) )
    // catch a freaking error
    .catch(error    => console.error(error) ); 
}
<button onclick="postData()">GET USERS</button>
suchislife
  • 4,251
  • 10
  • 47
  • 78

1 Answers1

3

GET request, you can only specify parameters in the URL, you should not have a body...

With a POST request, you can supply parameters in the body. A POST request can behave similar to a GET request, no problem.

AussieJoe
  • 1,285
  • 1
  • 14
  • 29
  • 3
    A GET request *can* have a body, but servers are obligated to ignore it. https://stackoverflow.com/questions/978061/http-get-with-request-body –  Aug 26 '19 at 15:56
  • 2
    So Ajax has been lying to me this whole time.. letting me do things I should receive errors for... – suchislife Aug 26 '19 at 15:57
  • @Amy I think this does it. "Whatever advantages that exist to using GET over POST, exist because of how HTTP is designed. Those advantages no longer exist, when you violate the standard in this way. Therefore there's only one reason left to use GET + a request body instead of POST: Aesthetics. Don't sacrifice robust design over aesthetics." – suchislife Aug 26 '19 at 16:02
  • @AussieJoe I don't know what you're disagreeing with, or why. The part you quoted isn't in conflict with anything I said. –  Aug 26 '19 at 16:06
  • @Amy I updated my answer, based on your reply. You still cannot have a body with a GET and make it work how he is proposing. It's misleading to imply that you CAN do it, but really CANNOT do it. – AussieJoe Aug 26 '19 at 16:08
  • @AussieJoe I never implied he could send data to the server with a GET body. I said the request *can* contain a body, and the server is obligated to ignore it. This is accurate, not misleading, and completely in agreement with the post that *I* cited. –  Aug 26 '19 at 16:09
  • I quoted because I found this part "..when you violate the standard in this way" to be very important to not do. Not to agree or disagree. You both bring good advice and clarity. – suchislife Aug 26 '19 at 16:12
  • @AussieJoe Again, I don't understand this disagreement. I never said it was useful. It's like you want to argue over something I never said, something I consider not useful. Maybe you should focus on things people say, rather than things you imagine they said. –  Aug 26 '19 at 16:16
  • Technically incorrect. You can specify and include parameters in the body. The server can parse that request and return responses dependent on that information; however, that is generally a bad idea. Not only do you break semantics of how a request is interpreted and intended, but you could have unintended side effects. For instance, GET requests tend to be browser (and server) cached, where the message body is often ignored, which means even if your request body changed, you’d most likely get the same cached response back for each fetch and good luck hunting that bug down. – vol7ron Aug 26 '19 at 17:51