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.

POSTJSONContent-Type

Form Submission

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

FormDataURL encoded

File Upload

Upload files with progress tracking and validation.

File APIprogress

Authentication Browser

Basic Authentication

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

AuthorizationBase64

Bearer Tokens

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

JWTBearerrefresh

Error Handling Browser

Error Responses

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

4xx5xxok property

Retry with Backoff

Automatic retry for failed requests with exponential backoff strategy.

retrybackoffresilience

Timeout Handling

Set request timeouts and handle slow responses gracefully.

AbortControllertimeout

CORS Browser

Simple CORS Requests

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

GETsimple headers

Preflight Requests

Understanding OPTIONS preflight and Access-Control headers.

OPTIONSpreflight

Credentials Mode

Sending cookies and auth headers with cross-origin requests.

credentialscookies

Caching Browser

Cache-Control Headers

Control browser caching behavior with proper Cache-Control directives.

Cache-Controlmax-age

ETag and Conditional Requests

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

ETag304If-None-Match

Server-Side Node.js

Basic HTTP Server

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

http modulecreateServer

Request Routing

Route requests by method and path without external frameworks.

routingURL parsing

JSON REST API

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

RESTCRUDvalidation