0
0
JavascriptHow-ToBeginner · 3 min read

How to Make GET Request in JavaScript: Simple Guide

To make a GET request in JavaScript, use the fetch() function with the URL you want to request. It returns a promise that resolves to the response, which you can convert to JSON or text using methods like response.json().
📐

Syntax

The basic syntax for a GET request using fetch() is simple. You call fetch() with the URL as the only argument. It returns a promise that resolves to a response object. You then use methods like response.json() to extract the data.

  • fetch(url): Starts the GET request to the given URL.
  • response.json(): Converts the response body to a JavaScript object.
  • then(): Handles the promise when it resolves.
  • catch(): Handles errors if the request fails.
javascript
fetch('https://example.com/data')
  .then(response => response.json())
  .then(data => {
    // Use the data here
  })
  .catch(error => {
    // Handle errors here
  });
💻

Example

This example fetches JSON data from a public API and logs the result to the console. It shows how to handle the response and errors.

javascript
fetch('https://jsonplaceholder.typicode.com/posts/1')
  .then(response => response.json())
  .then(data => {
    console.log('Post title:', data.title);
  })
  .catch(error => {
    console.error('Error fetching data:', error);
  });
Output
Post title: sunt aut facere repellat provident occaecati excepturi optio reprehenderit
⚠️

Common Pitfalls

Some common mistakes when making GET requests in JavaScript include:

  • Not handling the promise returned by fetch(), which leads to unhandled asynchronous code.
  • Forgetting to convert the response to JSON or text before using it.
  • Ignoring network errors by not using catch().
  • Assuming the response is always successful without checking response.ok.

Always check if the response is OK before processing data to avoid errors.

javascript
/* Wrong way: ignoring response status and errors */
fetch('https://jsonplaceholder.typicode.com/posts/1')
  .then(response => response.json())
  .then(data => console.log(data.title));

/* Right way: check response status and handle errors */
fetch('https://jsonplaceholder.typicode.com/posts/1')
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.json();
  })
  .then(data => console.log(data.title))
  .catch(error => console.error('Fetch error:', error));
📊

Quick Reference

TermDescription
fetch(url)Starts a GET request to the specified URL
response.json()Parses the response body as JSON
then()Handles the resolved promise
catch()Handles errors during the request
response.okBoolean indicating if the response was successful

Key Takeaways

Use fetch() with the URL to start a GET request in JavaScript.
Always convert the response to JSON or text before using it.
Check response.ok to ensure the request succeeded.
Handle errors with catch() to avoid unhandled promise rejections.
Promises require then() to process the response asynchronously.