Making HTTP Requests

JavaScript enables interaction with servers through HTTP requests to fetch or send data. The most common modern approach uses the fetch() API, which returns promises for asynchronous handling.

Illustration of Making HTTP Requests
Illustration of Making HTTP Requests

Basic GET Request with fetch()

Use fetch() with a URL to retrieve data. It returns a promise resolving to a Response object.

📌 Deep Dive: Simple GET Request

JAVASCRIPT
fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));
Output
Logs data object from the API or error message

Sending Data with POST Requests

To send data, specify method and body options. Usually, the body is serialized JSON.

📌 Deep Dive: POST Request Example

JAVASCRIPT
fetch('https://api.example.com/submit', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ name: 'Alice', age: 30 })
})
  .then(response => response.json())
  .then(result => console.log(result))
  .catch(error => console.error('Error:', error));
Output
Logs server response to POST submission

Common HTTP Methods

HTTP Methods Overview
MethodPurpose
GETRetrieve data from server
POSTSend new data to server
PUTUpdate existing data
DELETERemove data

💡 Handling Responses

Always check the response.ok property or status code before processing data to handle errors gracefully.

Using Async/Await for Cleaner Syntax

Async functions allow easier reading and error handling with try/catch.

📌 Deep Dive: Async/Await Fetch

JAVASCRIPT
async function getData() {
  try {
    const response = await fetch('https://api.example.com/data');
    if (!response.ok) throw new Error('Network response was not ok');
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Fetch error:', error);
  }
}
getData();
Output
Logs fetched data or error message

⚠️ CORS Restrictions

Cross-Origin Resource Sharing policies can block requests to different domains unless the server allows it via headers.

Summary

  • fetch() is the modern way to make HTTP requests in JavaScript.
  • It returns promises that resolve to response objects; parse with response.json() or response.text().
  • Set HTTP method, headers, and body in options for POST, PUT, DELETE requests.
  • Use async/await for more readable asynchronous code.
  • Always handle errors and check response status.