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>

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

9 Comments

A GET request can have a body, but servers are obligated to ignore it. stackoverflow.com/questions/978061/http-get-with-request-body
So Ajax has been lying to me this whole time.. letting me do things I should receive errors for...
@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."
@AussieJoe I don't know what you're disagreeing with, or why. The part you quoted isn't in conflict with anything I said.
@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.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.