Skip to content

JavaScript Fetch API: GET, POST, PUT, DELETE Requests and Handling Custom Headers

Master the Fetch API in JavaScript with comprehensive examples on making GET, POST, PUT, and DELETE requests.

Enhance your web development skills by learning how to handle custom headers for authentication and authorization.


GET Request

fetch('url', {
    headers: { 'Content-Type': 'application/json' }
  })
  .then(response => response.text())
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.error(error);
  });

POST Request

fetch('url', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ key: 'value' })
  })
  .then(response => response.text())
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.error(error);
  });

PUT Request

fetch('url', {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ key: 'value' })
  })
  .then(response => response.text())
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.error(error);
  });

DELETE Request

fetch('url', {
    method: 'DELETE',
    headers: { 'Content-Type': 'application/json' }
  })
  .then(response => response.text())
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.error(error);
  });

Handling Custom Headers

fetch('url', {
    headers: { 'Authorization': 'Bearer token' }
})
.then(response => response.text())
.then(data => {
    console.log(data);
})
.catch(error => {
    console.error(error);
});