HTTP Requests in JavaScript

Level : Advanced
Mentor: Shailendra Chauhan
Duration : 00:01:00

JSON-Formatted Response Body:

To handle JSON-formatted response bodies using the '.json()' method after making an HTTP request.

Example:

fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => {
    console.log(data);
  });

HTTP GET Request:

Make HTTP GET requests to retrieve information from a server using the Fetch API.

Example:

fetch('https://api.example.com/posts')
  .then(response => response.json())
  .then(posts => {
    console.log(posts);
  });

The fetch() Function:

Use the 'fetch()' function to initiate HTTP requests and handle responses using Promises.

Example:

fetch('https://api.example.com/data')
  .then(response => {
    if (response.ok) {
      return response.json();
    }
    throw new Error('Request failed!');
  })
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.error(error.message);
  });

Customizing Fetch Requests:

To customize fetch requests using options, such as specifying request headers, methods, and request bodies.

Example:

fetch('https://api.example.com/data', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({ key: 'value' })
})
.then(response => response.json())
.then(result => {
  console.log(result);
}); 

HTTP POST Request:

Making HTTP POST requests to send data to a server, usually to create or update resources.

Example:

const postData = { title: 'New Post', content: 'This is a new post.' };
fetch('https://api.example.com/posts', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(postData)
})
.then(response => response.json())
.then(newPost => {
  console.log(newPost);
}); 

Using async...await with Fetch:

To use the async...await syntax with the Fetch API for more concise and readable asynchronous code.

Example:

async function fetchData() {
  try {
    const response = await fetch('https://api.example.com/data');
    if (response.ok) {
      const data = await response.json();
      console.log(data);
    }
  } catch (error) {
    console.error(error);
  }
}
fetchData();
Self-paced Membership
  • 24+ Video Courses
  • 825+ Hands-On Labs
  • 400+ Quick Notes
  • 125+ Skill Tests
  • 10+ Interview Q&A Courses
  • 10+ Real-world Projects
  • Career Coaching Sessions
  • Email Support
Upto 60% OFF
Know More
Still have some questions? Let's discuss.
CONTACT US
Accept cookies & close this