Learn JavaScript · 11/15

Network Requests: Communicating with the World

9 min read

markdown
## 🌐 Network Requests: Communicating with the World

Welcome, future JavaScript maestro! So far, your code has been living in a cozy little bubble inside the user's browser. But what happens when you need data that isn't already in your code? Like fetching user profiles, loading product information, or finding out the weather in Timbuktu? Your code needs to talk to the outside world! This guide will show you how to make your JavaScript application communicate over the network to fetch and send data, making your web pages dynamic and powerful.

---

### 1. Introduction to APIs and JSON Data Format

#### The Problem: Data Isolation 🏝️

Imagine your web application is a brilliant librarian in a vast, empty library. This librarian knows how to organize and display books perfectly, but there's a catch: they have no books! The books (the data) are all stored in a massive, centralized warehouse (a server) miles away. How does our librarian get the specific books they need to show to visitors? They can't just teleport to the warehouse. They need a system to request them.

#### The Solution: APIs and JSON

This is where **APIs (Application Programming Interfaces)** come in. An API is like the library's catalog and dedicated courier service, all in one. It provides a clear menu of what can be requested from the warehouse and a set of rules for how to ask for it.

*   **API (Application Programming Interface):** An API is a contract between a client (your browser) and a server that defines how the two will communicate. You don't need to know *how* the server's warehouse is organized; you just need to know the correct way to ask the API for "all books on penguins" or "the book with ISBN 12345."

Once our librarian places an order, the warehouse sends the books. But how are they packaged? You can't just send a jumbled pile of pages. They need to be in a structured, easy-to-unpack format. This is where **JSON** comes in.

*   **JSON (JavaScript Object Notation):** JSON is the standard packaging format for sending data across the web. It's a lightweight, text-based format that is incredibly easy for humans to read and for JavaScript to understand (the "JSO" in "JSON" is for "JavaScript Object"). It was derived from JavaScript, and it represents structured data as a string, which is perfect for sending over a network.

**What does JSON look like?**

It's all about key-value pairs, just like JavaScript objects. The keys must be strings in double quotes, and the values can be a string, number, boolean, array, or another object.

```json
{
  "title": "The Hitchhiker's Guide to the Galaxy",
  "author": "Douglas Adams",
  "isAvailable": true,
  "pages": 224,
  "genres": ["Science Fiction", "Comedy"],
  "publisher": {
    "name": "Megadodo Publications",
    "location": "Ursa Minor Beta"
  }
}

This simple, structured format is the universal language for data on the web, and you'll be seeing a lot of it.


2. Fetching Data: Using the Fetch API for GET Requests

The Problem: Making the Request 🗣️

Okay, we know we need to ask the API for data, which will arrive in a neat JSON package. But how do we actually send the message from our JavaScript code?

The Solution: The fetch() API

Modern JavaScript has a powerful, built-in tool for this called the Fetch API. It provides a global fetch() method that makes requesting resources from a server incredibly straightforward. Think of it as your librarian's high-tech pneumatic tube system for sending request slips to the warehouse.

The fetch() method is a more powerful and flexible replacement for the older XMLHttpRequest. It takes one mandatory argument: the URL of the resource you want to fetch.

How fetch() Works: The Power of Promises

When you call fetch(), you don't get the data back instantly. Networks can be slow! Instead, fetch() immediately returns a Promise. A Promise is like a receipt from the courier service. It's a guarantee that you'll get a response eventually—either the data you asked for or a message that something went wrong.

Here’s the standard flow for a GET request (which is the default method):

javascript
fetch('https://api.example.com/data') // 1. Send the request
  .then(response => response.json())    // 2. When the server responds, parse the JSON
  .then(data => {                       // 3. Use the actual data
    console.log(data);
  })
  .catch(error => {                     // 4. If anything goes wrong
    console.error('There was a problem with the fetch operation:', error);
  });

Let's break that down:

  1. We call fetch() with the URL of the API endpoint we want to get data from.
  2. The .then() block is where we handle a successful response. The response object we get isn't the final data itself; it's the entire HTTP response. We need to tell JavaScript how to read the body of the response. Since we're expecting JSON, we call response.json(), which also returns a promise!
  3. We chain another .then() to handle the promise from response.json(). This is where we finally get our hands on the usable data (a JavaScript object/array).
  4. The .catch() block is our safety net. It will catch network errors (like if the user is offline).

Hands-On Example with a Real API

Let's use JSONPlaceholder, a fantastic free fake API for testing and prototyping. We'll fetch a list of "to-do" items.

javascript
// Let's fetch a list of todos from JSONPlaceholder
fetch('https://jsonplaceholder.typicode.com/todos?_limit=5') // We'll limit it to 5 for this example
  .then(response => {
    // Before we try to parse the JSON, let's make sure the request was successful!
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    return response.json();
  })
  .then(todos => {
    console.log("Here are the todos:");
    todos.forEach(todo => {
      console.log(`- ${todo.title} (Completed: ${todo.completed})`);
    });
  })
  .catch(error => {
    console.error('Could not fetch todos:', error);
  });

3. Sending Data: Configuring Fetch for POST Requests

The Problem: Sending Information Back 📤

Getting data is great, but what if you need to send data? For example, submitting a new user's information through a signup form, or posting a comment. A simple GET request won't work; we need to send a package to the server.

The Solution: Configuring the fetch Options

The fetch() function can take an optional second argument: an options object. This object lets us customize the request, including the HTTP method, headers, and the data we want to send (the body).

To send data, we typically use the POST method. Here are the key options you'll use:

  • method: We set this to 'POST'.
  • headers: This tells the server what kind of data we're sending. For JSON, we must include 'Content-Type': 'application/json'. This is like putting a "FRAGILE - CONTAINS JSON" sticker on our package.
  • body: This is the actual data. We must convert our JavaScript object into a JSON string using JSON.stringify() before sending it.

Hands-On Example: Creating a New Post

Let's use JSONPlaceholder again to create a new blog post.

javascript
const newPost = {
  title: 'My Awesome New Post',
  body: 'This is the content of my post. It is very insightful.',
  userId: 1
};

fetch('https://jsonplaceholder.typicode.com/posts', {
  method: 'POST', // 1. Specify the method
  headers: {      // 2. Set the headers
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(newPost) // 3. Stringify the JS object for the body
})
.then(response => {
  if (!response.ok) {
    throw new Error(`HTTP error! Status: ${response.status}`);
  }
  return response.json();
})
.then(data => {
  console.log("Success! The server responded with:", data);
  // The server will usually respond with the created object, including its new ID
})
.catch(error => {
  console.error('Error creating post:', error);
});

4. Handling Loading States and Network Errors Gracefully

The Problem: The Awkward Silence ⏳ and Total Failure 💥

Network requests are not instant. While the browser is waiting for the server, your user sees... nothing. This can make your app feel slow or broken.

Worse, what if the request fails? The user's internet could disconnect, or the server could be down. If you don't handle this, your app will crash, and the user will be left confused and frustrated.

The Solution: User Feedback and Error Catching

1. Handling Loading States

The professional way to handle the "waiting" period is to show the user a loading indicator (like a spinner). The logic is simple:

  1. Just before you call fetch(), show the loading indicator.
  2. Once the request is complete (whether it succeeded or failed), hide the indicator. The .finally() method of a Promise is perfect for this, as it runs regardless of the outcome.
javascript
// Assume you have functions to show/hide a spinner
// showLoadingSpinner();

fetch('https://jsonplaceholder.typicode.com/users/1')
  .then(response => response.json())
  .then(data => {
    console.log(data);
    // displayUserData(data);
  })
  .catch(error => {
    console.error("Fetch failed:", error);
    // displayErrorMessage("Could not load user data.");
  })
  .finally(() => {
    // This will run no matter what, perfect for hiding a loader!
    // hideLoadingSpinner();
    console.log("Fetch attempt finished.");
  });

2. Handling Network and Server Errors

This is one of the most important—and trickiest—parts of working with fetch.

Funny but true fact: fetch() has a weird quirk. A fetch() promise only rejects (triggers the .catch() block) when there's a network error, like the internet being disconnected. If the server responds with an error code like 404 Not Found or 500 Internal Server Error, fetch() considers it a successful request because, hey, it got a response!

This means we have to manually check if the response was okay. The response.ok property is a boolean that is true only for successful HTTP statuses (like 200-299).

The industry-standard practice is to check response.ok in the first .then() block and, if it's false, throw an error yourself to trigger the .catch() block.

javascript
fetch('https://jsonplaceholder.typicode.com/post/9999') // This post does not exist, so it will cause a 404 error
  .then(response => {
    console.log("Received a response, but checking if it's okay...");
    // The most important step for error handling!
    if (!response.ok) {
      // Throw an error to be caught by the .catch() block
      throw new Error(`Server responded with an error! Status: ${response.status}`);
    }
    return response.json();
  })
  .then(data => {
    // This part will be skipped because an error was thrown above
    console.log("This will not be logged.", data);
  })
  .catch(error => {
    // Our .catch() block will now handle both network errors AND server errors!
    console.error("Caught an error:", error.message);
  });

By mastering these four areas, you can transform your static web pages into dynamic, interactive applications that can communicate with servers all over the world. Happy fetching! 🚀


📚 Further Reading & Resources

text

Challenge

Challenge: Update User Profile

Your task is to implement the updateUserProfile function. This function must perform a sequence of network operations to update a user's profile on a server.

Requirements:

  1. The function should accept a userId and an updatedData object.
  2. First, perform a GET request to https://api.example.com/users/{userId} to fetch the existing user data.
  3. After receiving the response, you must check if the response was successful using the response.ok property. If it's not ok, you must throw a new Error with the message "Failed to fetch user data.".
  4. If the GET request is successful, parse the JSON body from the response.
  5. Create a new object by merging the fetched user data with the updatedData provided to the function. The properties in updatedData should overwrite any existing properties.
  6. Next, perform a POST request to the same URL (https://api.example.com/users/{userId}) to send the new, merged user profile.
  7. This POST request must be configured with the correct method, headers to specify the Content-Type as application/json, and a body containing the JSON stringified version of the merged profile data.
  8. The function should return the promise chain.
  9. Include a final .catch() block that logs the error message to the console (e.g., console.error(error.message)).

Expected result

The updateUserProfile function should be fully implemented according to the instructions. The code must contain a fetch call for the GET request, followed by a .then() block that includes a check for response.ok and throws an error if it's false. It should then call response.json(). A subsequent .then() block should handle the merging of data and initiate a second fetch call for the POST request. This POST request must be configured with an options object specifying the method as 'POST', headers as {'Content-Type': 'application/json'}, and the body as the result of JSON.stringify() on the merged data. The entire chain must end with a .catch() block to handle any potential errors.

javascript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.