vikramlc / Javascript

0 stars 0 forks source link

Working with Http requests #18

Open vikramlc opened 4 years ago

vikramlc commented 4 years ago

Sending a GET request:

const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts');

xhr.onload = function() {
  console.log(xhr.response);
};

xhr.send();

JSON data and parsing data:

const listElement = document.querySelector('.posts');
const postTemplate = document.getElementById('single-post');

const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts');

xhr.responseType = 'json';

xhr.onload = function() {
  // const listOfPosts = JSON.parse(xhr.response);
  const listOfPosts = xhr.response;
  for (const post of listOfPosts) {
    const postEl = document.importNode(postTemplate.content, true);
    postEl.querySelector('h2').textContent = post.title.toUpperCase();
    postEl.querySelector('p').textContent = post.body;
    listElement.append(postEl);
  }
};

xhr.send();
vikramlc commented 4 years ago

Sending POST requests:

function sendHttpRequest(method, url, data) {
  const promise = new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    // xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts');
    xhr.open(method, url);

    xhr.responseType = 'json';

    xhr.onload = function() {
      resolve(xhr.response);
      // const listOfPosts = JSON.parse(xhr.response);

    };

    xhr.send(JSON.stringify(data));
  });

  return promise;
}

async function createPost(title, content) {
  const userId = Math.random();
  const post = {
    title: title,
    content: content,
    userId: userId
  };

  sendHttpRequest('POST', 'https://jsonplaceholder.typicode.com/posts', post);
}

fetchPosts();
createPost('A dummy title', 'A dummy content');
vikramlc commented 4 years ago

Error handling with Http requests

// Error handling is triggered when there is an error from the API call.
    xhr.onload = function() {
      if (xhr.status >= 200 && xhr.status < 300) {
        resolve(xhr.response);
      } else {
        reject(new Error('Something went wrong!!'));
      }
      // const listOfPosts = JSON.parse(xhr.response);

    };

    // This is triggered if there is any network error like timeout or no internet
    xhr.onerror = function() {
      reject(new Error('Failed to send request.'));
    };
vikramlc commented 4 years ago

Http Requests with fetch() method

return fetch(url, {
    method: 'POST',
    body: JSON.stringify(data)
  }).then(response => {
    return response.json();
  });
vikramlc commented 4 years ago

fetch() and error handling

return fetch(url, {
    method: method,
    body: JSON.stringify(data),
    headers: {
      'Content-Type': 'application/json'
    }
  })
  .then(response => {
    if (response.status >= 200 && response.status < 300) {
      return response.json();
    } else {
      return response.json().then(errData => {
        console.log(errData);
        throw new Error('Something went wrong - server-side.');
      });
    }
  })
  .catch(error => {
    console.log(error);
  });
vikramlc commented 4 years ago

Note: We can send data to the API using the form data. We cannot send the json data directly using the form data. We need to send it through a object.

The advantage is we can send files easily with the form data.