JavaScript Fetch

We can send or get data from remote server using Fetch API in JavaScript. The fetch method will retrun a Promisewhich will need to be handled using Promise .then or the syntactic sugar async-await.

An example of GET request, a method for getting data from server:

const fakeJSONGetResponse = await fetch('https://jsonplaceholder.typicode.com/posts/1')

const fakeJSONGetData  = await fakeJSONGetResponse.json()

console.log({fakeJSONGetData})

An example of POST request, a method for sending data to a server:

const fakeJSONPostResponse = await fetch('https://jsonplaceholder.typicode.com/posts', {
    method: 'POST',
    body: JSON.stringify({
      title: 'foo',
      body: 'bar',
      userId: 1
    }),
    headers: {
      "Content-type": "application/json; charset=UTF-8"
    }
  })

const fakeJSONPostData  = await fakeJSONPostResponse.jason()

console.log({fakeJSONPostData})

An example of PUT request, a method for complete update on all properties:

const fakeJSONPutResponse  = await fetch('https://jsonplaceholder.typicode.com/posts/1', {
    method: 'PUT',
    body: JSON.stringify({
      id: 1,
      title: 'foo',
      body: 'bar',
      userId: 1
    }),
    headers: {
      "Content-type": "application/json; charset=UTF-8"
    }
  })

const fakeJSONPutData = await fakeJSONPutResponse.json()

console.log({fakeJSONPutData})

An example of PATCH request, a method for partially updating data:

const fakeJSONPatchResponse = await fetch('https://jsonplaceholder.typicode.com/posts/1', {
    method: 'PATCH',
    body: JSON.stringify({
      title: 'foo'
    }),
    headers: {
      "Content-type": "application/json; charset=UTF-8"
    }
  })

const fakeJSONPatchData = await fakeJSONPatchResponse.json()

console.log({fakeJSONPatchData})

An example of DELETE request, a method for deleting data:

const fakeDeleteResponse = await fetch('https://jsonplaceholder.typicode.com/posts/1', {
  method: 'DELETE'
})

const fakeDeleteData = await fakeDeleteResponse.json()

console.log({fakeDeleteData})

References:

  • Using Fetch (https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch)
  • JSONPlaceholder (https://jsonplaceholder.typicode.com/guide.html)

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.