Code-Alongs - Web Unit 3 Sprint 11

Code-Alongs Overview

Code-Alongs are live experiences taught by expert instructors designed to prepare you for concepts found in the sprint challenges. These sessions are your opportunity to work on complex job-ready problems in a live and engaging environment.

Code-Alongs are live classes 50 minutes in length designed to offer deeper insights into learning your core competencies and are offered seven days a week in the morning, afternoon, and evening.

Code-Along Sessions

Code-Along 1: Authorization

Understanding Login Requests

This code-along builds on the fundamental concept of login requests in web development. You'll learn how a simple action like logging into a website involves making a network request, focusing on the POST request method, headers, and payloads.

The Request-Response Cycle

When you enter credentials on a login page, you're sending a POST request to the server with:

  • Headers - Key-value pairs with information about the request
  • Payload - The data being sent (typically in JSON format)

The server processes this request and sends back a response with its own headers and body, which might contain a welcome message or an error code like 401 Unauthorized.

Using Authentication Tokens

In successful login attempts, the server responds with a token—a string that represents your authentication status. This token is crucial for:

  • Subsequent requests to access protected resources
  • Web security and session management
  • Maintaining user state across the application
Implementation Example
// Login request
const loginUser = async (credentials) => {
  try {
    const response = await fetch('https://api.example.com/login', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(credentials)
    });
    
    if (!response.ok) {
      throw new Error('Login failed');
    }
    
    const data = await response.json();
    // Store the token for future requests
    localStorage.setItem('authToken', data.token);
    return data;
  } catch (error) {
    console.error('Error during login:', error);
    throw error;
  }
};
Tools for Inspecting HTTP Traffic

During this code-along, you'll learn to use powerful tools for inspecting and debugging HTTP traffic:

  • Chrome Developer Tools - Examine network requests and responses in real-time
  • HTTPie - A command-line HTTP client for testing API endpoints
  • Postman - A comprehensive API development platform for constructing and testing requests

Code-Along 2: PUT Requests

Configuring Fetch Requests

In this code-along, you'll learn how to use the fetch API in JavaScript to make more complex HTTP requests like POST, PUT, and DELETE. You'll explore how to customize these requests using the second argument of fetch to specify the method, body, and headers.

Making PUT Requests

PUT requests are used to update existing resources on a server. The key components include:

  • Specifying 'PUT' as the method
  • Including the correct Content-Type header
  • Providing a properly formatted body with the updated data
  • Handling the response appropriately
Implementation Example
// PUT request to update a resource
const updateResource = async (id, updatedData) => {
  try {
    // Get the auth token from localStorage
    const token = localStorage.getItem('authToken');
    
    const response = await fetch(`https://api.example.com/resources/${id}`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
      body: JSON.stringify(updatedData)
    });
    
    if (!response.ok) {
      throw new Error('Update failed');
    }
    
    return await response.json();
  } catch (error) {
    console.error('Error updating resource:', error);
    throw error;
  }
};
CRUD Operations with Fetch

This code-along will help you understand how to perform all CRUD (Create, Read, Update, Delete) operations using the Fetch API:

  • Create - POST requests to add new resources
  • Read - GET requests to retrieve resources
  • Update - PUT requests to modify existing resources
  • Delete - DELETE requests to remove resources
Error Handling

You'll also learn proper error handling techniques for network requests, including:

  • Checking response status codes
  • Implementing try/catch blocks
  • Providing meaningful error feedback to users
  • Handling network failures gracefully

Preparation Checklist

Additional Resources