0
0
JavascriptHow-ToBeginner · 4 min read

How to Make HTTP Request in JavaScript: Simple Guide

You can make an HTTP request in JavaScript using the fetch() function, which sends a request and returns a promise with the response. Use fetch(url) to get data from a server, then handle the response with .then() or async/await.
📐

Syntax

The basic syntax for making an HTTP request with fetch() is:

  • fetch(url, options): Sends a request to the given URL.
  • url: The address of the resource you want to get or send data to.
  • options: An optional object to specify method (GET, POST, etc.), headers, body, and other settings.
  • The function returns a Promise that resolves to a Response object.
javascript
fetch('https://example.com/api/data', {
  method: 'GET', // or 'POST', 'PUT', etc.
  headers: {
    'Content-Type': 'application/json'
  },
  // body: JSON.stringify({ key: 'value' }) // only for methods like POST
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
💻

Example

This example shows how to make a GET request to fetch JSON data from a public API and log the result.

javascript
async function getUser() {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/users/1');
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    const user = await response.json();
    console.log(user);
  } catch (error) {
    console.error('Fetch error:', error);
  }
}

getUser();
Output
{ "id": 1, "name": "Leanne Graham", "username": "Bret", "email": "Sincere@april.biz", "address": { "street": "Kulas Light", "suite": "Apt. 556", "city": "Gwenborough", "zipcode": "92998-3874", "geo": { "lat": "-37.3159", "lng": "81.1496" } }, "phone": "1-770-736-8031 x56442", "website": "hildegard.org", "company": { "name": "Romaguera-Crona", "catchPhrase": "Multi-layered client-server neural-net", "bs": "harness real-time e-markets" } }
⚠️

Common Pitfalls

Common mistakes when making HTTP requests in JavaScript include:

  • Not checking if the response is successful before parsing JSON.
  • Forgetting to handle network errors with catch or try/catch.
  • Using fetch() without specifying method or headers when needed.
  • Trying to parse non-JSON responses with response.json().
javascript
/* Wrong way: Not checking response status */
fetch('https://jsonplaceholder.typicode.com/users/1')
  .then(response => response.json()) // might fail if response is not ok
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

/* Right way: Check response.ok before parsing */
fetch('https://jsonplaceholder.typicode.com/users/1')
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.json();
  })
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));
📊

Quick Reference

Here are quick tips for making HTTP requests with fetch():

  • Use GET method by default for fetching data.
  • Use POST with body for sending data.
  • Always check response.ok before processing data.
  • Handle errors with catch or try/catch.
  • Use async/await for cleaner asynchronous code.

Key Takeaways

Use the fetch() function to make HTTP requests easily in JavaScript.
Always check if the response is successful before parsing the data.
Handle errors properly to avoid uncaught exceptions.
Use async/await syntax for clearer and more readable code.
Specify method, headers, and body in fetch options when needed.