Using HTML 5 Fetch API to consume JSON

I have split the front end app from backend Rails API app in my current project. I was looking for simple way to interact with a remote server and consume JSON. HTML 5 includes a Fetch API that we can use. In this article, we will see how to make a post request using the Fetch API. Install node. Before upgrade I had:

$ node -v
v9.5.0
$ npm -v
5.6.0

After upgrade:

$ node -v
v9.8.0
$ npm -v
5.6.0

Install a simple Node HTTP server

npm install http-server -g

Start the local server:

http-server

You can install live-server if you want the browser to refresh automatically when the file is saved. Here is a simple GET request using the Fetch API:

<script>
  fetch('https://jsonplaceholder.typicode.com/posts/1')
    .then(response => response.json())
    .then(json => console.log(json))
</script>

Here is the POST request:

fetch('http://jsonplaceholder.typicode.com/posts', {  
    method: 'POST',  
    body: JSON.stringify({
    title: 'testing post',
    body: 'did you get it',
  })
})
.then(function (data) {  
  console.log('Request success: ', data);  
})  
.catch(function (error) {  
  console.log('Request failure: ', error);  
});

Let's take the user filled out form and submit to the server:

<!DOCTYPE html>
<html>
  <head>
    <title>Fetch POST example</title>
  </head>
  <body class="container">
    <h1>Testing</h1>
  <form method="POST" action="" id="form">
    <p>
      Title: <input type="text" name="title" id='title'/>
    </p>
    <p>
      Body <textarea id="body" class="form-control" name='body' rows="5"></textarea>
    </p>
    <p>
      <button type="submit">Submit</button>
    </p>
  </form>

  <div id="results"></div>
    <script>
      var formEl = document.getElementById('form');
      formEl.addEventListener('submit', function(event) {
        // 1. Setup the request
        // ================================
        // 1.1 Headers
        var headers = new Headers();
        // Tell the server we want JSON back
        headers.set('Accept', 'application/json');
        // 1.2 Form Data
        // We need to properly format the submitted fields.
        // Here we will use the same format the browser submits POST forms.
        // You could use a different format, depending on your server, such
        // as JSON or XML.
        var formData = new FormData();
        for (var i = 0; i < formEl.length; ++i) {
          formData.append(formEl[i].name, formEl[i].value);
        }
        // This is for the purpose of this demo using jsFiddle AJAX Request endpoint
        var title = document.getElementById('title').value;
        var body = document.getElementById('body').value;

        formData.append('json', JSON.stringify({title: 'title', body: 'body'}));
        // 2. Make the request
        // ================================
        var url = 'http://jsonplaceholder.typicode.com/posts';
        var fetchOptions = {
          method: 'POST',
          headers,
          body: formData
        };
        var responsePromise = fetch(url, fetchOptions);
        // 3. Use the response
        // ================================
        responsePromise
            // 3.1 Convert the response into JSON-JS object.
          .then(function(response) {
            return response.json();
          })
          // 3.2 Do something with the JSON data
          .then(function(jsonData) {
            console.log(jsonData);
            document.getElementById('results').innerText =
                JSON.stringify(jsonData);
          });
        event.preventDefault();
      });
    </script>
  </body>
</html>

It took me a few hours to get this to work by putting bits and pieces from different resources into one working example. I hope you find this helpful.

References

Simple Fetch API Post example
Google Developers Fetch API
JS Fiddle Example


Related Articles


Create your own user feedback survey