ūüŹ° Home

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: