HTTP Examples

Working code for real-world HTTP patterns

Learn by Example

These examples demonstrate practical HTTP patterns using vanilla JavaScript. Each example shows complete, working code you can study, copy, and adapt for your projects.

Client-side examples use the Fetch API and run in the browser. Server-side examples use Node.js built-in modules with no external dependencies.

Client-Side Requests Browser

Basic GET Request

Fetch data from an API with proper error handling and response parsing.

fetch() async/await

POST with JSON

Send JSON data to a server with correct headers and body encoding.

POST JSON Content-Type

Form Submission

Submit forms with FormData, URL encoding, and different content types.

FormData URL encoded

File Upload

Upload files with progress tracking and validation.

File API progress

Authentication Browser

Basic Authentication

HTTP Basic Auth with base64-encoded credentials in the Authorization header.

Authorization Base64

Bearer Tokens

Token-based auth with JWT, including storage, refresh, and expiration handling.

JWT Bearer refresh

Error Handling Browser

Error Responses

Handle HTTP error status codes gracefully with user-friendly messages.

4xx 5xx ok property

Retry with Backoff

Automatic retry for failed requests with exponential backoff strategy.

retry backoff resilience

Timeout Handling

Set request timeouts and handle slow responses gracefully.

AbortController timeout

CORS Browser

Simple CORS Requests

Cross-origin requests that don't trigger preflight checks.

GET simple headers

Preflight Requests

Understanding OPTIONS preflight and Access-Control headers.

OPTIONS preflight

Credentials Mode

Sending cookies and auth headers with cross-origin requests.

credentials cookies

Caching Browser

Cache-Control Headers

Control browser caching behavior with proper Cache-Control directives.

Cache-Control max-age

ETag and Conditional Requests

Conditional requests with ETag and If-None-Match for cache validation.

ETag 304 If-None-Match

Server-Side Node.js

Basic HTTP Server

Create a minimal HTTP server with Node.js built-in http module.

http module createServer

Request Routing

Route requests by method and path without external frameworks.

routing URL parsing

JSON REST API

Build a RESTful JSON API with validation and proper status codes.

REST CRUD validation