This cheatsheet provides a comprehensive reference for HTTP Status Codes, HTTP Headers, and CORS (Cross-Origin Resource Sharing) configuration. It’s designed for quick lookup, practical examples, and best practices for developers and tech professionals working with web APIs and services.


Quick Reference

ConceptDescriptionCommon Example / Syntax
HTTP StatusServer’s response to a client’s request, indicating success or failure.200 OK, 404 Not Found, 500 Internal Server Error
HTTP HeaderMetadata sent with HTTP requests and responses.Content-Type: application/json, Authorization: Bearer ...
CORSMechanism allowing web pages to request resources from a different domain.Access-Control-Allow-Origin: https://example.com
GETRequest data from a specified resource.GET /users/123
POSTSubmit data to be processed to a specified resource.POST /users (with JSON body)
PUTUpdate a specified resource.PUT /users/123 (with JSON body)
DELETEDelete a specified resource.DELETE /users/123
OPTIONSDescribe the communication options for the target resource (CORS preflight).OPTIONS /api/data

HTTP Status Codes

HTTP status codes are three-digit numbers returned by a server in response to a client’s request. They are grouped into five classes, indicating the nature of the response.

1xx: Informational Responses

Indicates that the request was received and understood.

CodeNameDescriptionExample Use Case
100ContinueClient should continue with its request.Sent by server to client after receiving request headers, prompting client to send request body.
101Switching ProtocolsServer is switching protocols.Used in WebSocket handshake to upgrade connection from HTTP to WebSocket.

2xx: Success Responses

Indicates that the action requested by the client was received, understood, and accepted.

CodeNameDescriptionExample Use Case
200OKStandard response for successful HTTP requests.Successful GET, PUT, PATCH, DELETE requests.
201CreatedRequest has been fulfilled and a new resource created.Successful POST request creating a new user or resource.
202AcceptedRequest accepted for processing, but not yet completed.Asynchronous processing where the request will eventually be fulfilled.
204No ContentServer successfully processed the request, but is not returning any content.Successful DELETE request where no response body is needed.

3xx: Redirection Messages

Indicates that further action needs to be taken by the user agent to fulfill the request.

CodeNameDescriptionExample Use Case
301Moved PermanentlyResource has been permanently moved to a new URL.Old URL redirects to a new, permanent URL for a resource.
302Found (formerly Moved Temporarily)Resource has been temporarily moved to a new URL.Redirecting a user to a login page after session expiration.
304Not ModifiedResource has not been modified since the version specified by the request headers.Client has a cached version and it’s still fresh, saving bandwidth.

4xx: Client Error Responses

Indicates that the client appears to have made an error.

CodeNameDescriptionExample Use Case
400Bad RequestServer cannot process the request due to client error (e.g., malformed syntax).Invalid JSON payload, missing required parameters.
401UnauthorizedRequest requires user authentication.Accessing a protected resource without a valid authentication token.
403ForbiddenServer understood the request but refuses to authorize it.User is authenticated but lacks necessary permissions for the resource.
404Not FoundServer cannot find the requested resource.Requesting a non-existent API endpoint or resource ID.
405Method Not AllowedRequest method is known by the server but not supported for the target resource.Trying to POST to a read-only endpoint that only accepts GET.
409ConflictRequest conflicts with the current state of the target resource.Trying to create a resource that already exists (e.g., duplicate username).
429Too Many RequestsUser has sent too many requests in a given amount of time.Rate limiting applied to API calls.

5xx: Server Error Responses

Indicates that the server failed to fulfill an apparently valid request.

CodeNameDescriptionExample Use Case
500Internal Server ErrorGeneric error message when an unexpected condition was encountered.Unhandled exception in the server application logic.
502Bad GatewayServer acting as a gateway/proxy received an invalid response from an upstream server.Backend service is down or unresponsive behind a proxy.
503Service UnavailableServer is not ready to handle the request (e.g., overloaded or down for maintenance).Server temporarily unable to handle requests, often with a Retry-After header.
504Gateway TimeoutServer acting as a gateway/proxy did not receive a timely response from an upstream server.Backend service took too long to respond.

HTTP Headers

HTTP headers provide essential metadata about the request or response. They are key-value pairs separated by a colon.

General Headers

Apply to both requests and responses.

HeaderDescriptionExample
Cache-ControlDirectives for caching mechanisms.Cache-Control: no-cache, max-age=3600
ConnectionControl whether the network connection stays open after the current transaction.Connection: keep-alive
DateThe date and time at which the message was originated.Date: Tue, 15 Nov 2025 08:12:31 GMT
Transfer-EncodingEncoding applied to the payload body.Transfer-Encoding: chunked

Request Headers

Specific to client requests.

HeaderDescriptionExample
AcceptMedia types that are acceptable for the response.Accept: application/json, text/plain
Accept-EncodingContent encodings that are acceptable for the response.Accept-Encoding: gzip, deflate
AuthorizationCredentials for authenticating a user agent with a server.Authorization: Bearer <token>
Content-TypeMedia type of the resource in the request body.Content-Type: application/json
HostDomain name of the server (for virtual hosting).Host: api.example.com
User-AgentInformation about the user agent (browser, client).User-Agent: Mozilla/5.0 (...) Chrome/...
RefererAddress of the previous web page from which a link was followed.Referer: https://www.example.com/page
OriginIndicates the origin of the cross-origin request (for CORS).Origin: https://client.example.com

Response Headers

Specific to server responses.

HeaderDescriptionExample
Content-TypeMedia type of the resource in the response body.Content-Type: application/json; charset=utf-8
Content-LengthSize of the resource body, in bytes.Content-Length: 1024
ETagAn identifier for a specific version of a resource.ETag: "abcdef123"
LocationUsed in redirection (3xx) or resource creation (201) to indicate the new URL.Location: /new-resource/123
ServerInformation about the software used by the origin server.Server: Nginx/1.25.3
Set-CookieSends cookies from the server to the user agent.Set-Cookie: sessionid=abc; HttpOnly; Secure
WWW-AuthenticateDefines the authentication method that should be used to gain access to a resource.WWW-Authenticate: Basic realm="Access to API"
AllowList of HTTP methods supported by a resource.Allow: GET, HEAD, OPTIONS

Used for Cross-Origin Resource Sharing.

HeaderDescriptionExample
Access-Control-Allow-OriginIndicates whether the response can be shared with requesting code from the given origin.Access-Control-Allow-Origin: https://client.example.com or * (wildcard, use with caution)
Access-Control-Allow-MethodsIndicates the HTTP methods allowed when accessing the resource.Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-HeadersIndicates which HTTP headers can be used when making the actual request.Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With
Access-Control-Expose-HeadersIndicates which headers can be exposed as part of the response by listing their names.Access-Control-Expose-Headers: X-Custom-Header
Access-Control-Max-AgeIndicates how long the results of a preflight request can be cached.Access-Control-Max-Age: 86400 (24 hours)
Access-Control-Allow-CredentialsIndicates whether the response to the request can be exposed when the credentials flag is true.Access-Control-Allow-Credentials: true

CORS Configuration

Cross-Origin Resource Sharing (CORS) is a security feature implemented by web browsers that prevents web pages from making requests to a different domain than the one that served the web page, unless the server explicitly allows it.

Basic Concepts

  • Origin: A combination of scheme (protocol), host (domain), and port. https://example.com:8080 is a different origin from http://example.com:8080 or https://sub.example.com.
  • Simple Request: A request that meets certain criteria (e.g., GET, HEAD, POST with specific Content-Type headers). These requests are sent directly, and the browser checks the Access-Control-Allow-Origin header in the response.
  • Preflight Request: For “non-simple” requests (e.g., PUT, DELETE, PATCH, or POST with Content-Type: application/json), the browser first sends an OPTIONS request to the server. This “preflight” asks the server for permission to send the actual request. The server must respond with appropriate Access-Control-Allow-* headers.

CORS Configuration Examples

Node.js (Express with cors middleware)

This is the most common way to handle CORS in Express.

// Install: npm install cors
const express = require('express');
const cors = require('cors');
const app = express();

// Basic usage: Allow all origins (NOT recommended for production)
app.use(cors());

// Allow specific origins
const allowedOrigins = ['https://client.example.com', 'https://another-client.com'];
app.use(cors({
  origin: function (origin, callback) {
    // allow requests with no origin (like mobile apps or curl requests)
    if (!origin) return callback(null, true);
    if (allowedOrigins.indexOf(origin) === -1) {
      const msg = 'The CORS policy for this site does not allow access from the specified Origin.';
      return callback(new Error(msg), false);
    }
    return callback(null, true);
  },
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], // Explicitly allowed methods
  allowedHeaders: ['Content-Type', 'Authorization', 'X-Custom-Header'], // Explicitly allowed headers
  credentials: true, // Allow cookies, authorization headers, TLS client certificates
  maxAge: 86400 // Cache preflight response for 24 hours
}));

// Example route
app.get('/api/data', (req, res) => {
  res.json({ message: 'Data from API' });
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});

Explanation: The cors middleware simplifies CORS header management. You can configure origin, methods, allowedHeaders, credentials, and maxAge to control access. Use Case: Ideal for Node.js applications using the Express framework.

Nginx

Configure CORS headers within your server or location block.

# /etc/nginx/nginx.conf or a site-specific config file
server {
    listen 80;
    server_name api.example.com;

    # Basic CORS for all origins (use with caution)
    # add_header 'Access-Control-Allow-Origin' '*';

    # Allow specific origin
    location / {
        if ($request_method = 'OPTIONS') {
            add_header 'Access-Control-Allow-Origin' 'https://client.example.com';
            add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
            add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization';
            add_header 'Access-Control-Max-Age' 1728000;
            add_header 'Content-Type' 'text/plain; charset=utf-8';
            add_header 'Content-Length' 0;
            return 204;
        }
        add_header 'Access-Control-Allow-Origin' 'https://client.example.com';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization';
        # If you need to allow credentials (cookies, HTTP authentication)
        # add_header 'Access-Control-Allow-Credentials' 'true';

        # Proxy pass to your backend application
        proxy_pass http://localhost:3000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

Explanation: Nginx handles preflight OPTIONS requests separately. Headers are added using add_header. The return 204 for OPTIONS requests is crucial for preflight success. Use Case: When Nginx acts as a reverse proxy for your API backend.

Apache HTTP Server

Configure CORS headers in .htaccess files or within VirtualHost configurations. Ensure mod_headers is enabled (a2enmod headers).

# In .htaccess or <VirtualHost> block
<IfModule mod_headers.c>
    # Allow specific origin
    Header set Access-Control-Allow-Origin "https://client.example.com"
    # Or allow multiple origins (requires logic, e.g., using SetEnvIf)
    # SetEnvIf Origin "https?://(www\.)?(client\.example\.com|another\.client\.com)$" AccessControlAllowOrigin=$0
    # Header set Access-Control-Allow-Origin "%{AccessControlAllowOrigin}e" env=AccessControlAllowOrigin
    # Header unset Access-Control-Allow-Origin env=!AccessControlAllowOrigin

    Header set Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"
    Header set Access-Control-Allow-Headers "Content-Type, Authorization, X-Requested-With"
    Header set Access-Control-Max-Age "86400"
    # If you need to allow credentials
    # Header set Access-Control-Allow-Credentials "true"

    # Handle preflight OPTIONS requests
    RewriteEngine On
    RewriteCond %{REQUEST_METHOD} OPTIONS
    RewriteRule ^(.*)$ $1 [R=204,L]
</IfModule>

Explanation: Apache uses Header set directives. For OPTIONS requests, a RewriteRule can be used to return 204 No Content and prevent further processing. Use Case: When Apache serves your static files or acts as a reverse proxy.


Common Patterns

1. Handling Successful API Responses

// GET /users/123 (200 OK)
{
  "id": "123",
  "name": "Alice Doe",
  "email": "[email protected]"
}

// POST /users (201 Created)
{
  "id": "456",
  "name": "Bob Smith",
  "email": "[email protected]",
  "message": "User created successfully."
}

Explanation: For GET, return the requested resource. For POST (creation), return the newly created resource along with 201 Created and a Location header pointing to the new resource.

2. Handling Client-Side Errors

// POST /users (invalid data, 400 Bad Request)
{
  "code": "BAD_REQUEST",
  "message": "Validation failed",
  "details": [
    { "field": "email", "error": "Invalid email format" },
    { "field": "password", "error": "Password must be at least 8 characters" }
  ]
}

// GET /products/999 (not found, 404 Not Found)
{
  "code": "NOT_FOUND",
  "message": "Product with ID '999' not found."
}

Explanation: Provide clear, machine-readable error messages with 4xx status codes. Include specific details to help the client correct their request.

3. Implementing Secure CORS

Always specify allowed origins, methods, and headers. Avoid using Access-Control-Allow-Origin: * in production unless your API is truly public and does not handle sensitive user data (e.g., a public image CDN).

// Node.js (Express) - Secure CORS
app.use(cors({
  origin: 'https://your-frontend-domain.com', // Specific origin
  methods: ['GET', 'POST', 'PUT', 'DELETE'], // Only necessary methods
  allowedHeaders: ['Content-Type', 'Authorization'], // Only necessary headers
  credentials: true // Only if you need to send cookies/auth headers
}));

Explanation: Restricting CORS to specific origins and methods minimizes the attack surface.

4. Caching with Headers

Utilize Cache-Control and ETag for efficient caching.

HTTP/1.1 200 OK
Content-Type: application/json
Cache-Control: public, max-age=3600
ETag: "v1.2-abcdef"

// Client sends:
If-None-Match: "v1.2-abcdef"

// Server responds (if resource unchanged):
HTTP/1.1 304 Not Modified

Explanation: Cache-Control tells the browser/proxy how long to cache the resource. ETag provides a unique identifier for the resource version. If-None-Match allows the client to ask the server if its cached version is still valid, leading to a 304 Not Modified response if so, saving bandwidth.


Tips & Tricks

  • Choose the Right Status Code: Don’t just default to 500 for all errors. Be precise with 4xx and 5xx codes to give clients meaningful feedback.
  • Idempotency: GET, PUT, DELETE, and HEAD methods should be idempotent, meaning making the same request multiple times has the same effect as making it once. POST is generally not idempotent.
  • CORS Debugging:
    • Check browser developer tools (Network tab) for OPTIONS requests and their responses.
    • Look for CORS errors in the browser console.
    • Use curl -v -H "Origin: https://bad.origin.com" -X OPTIONS http://your-api.com/resource to simulate preflight requests.
  • Security Headers: Beyond CORS, consider other security headers like Strict-Transport-Security, X-Content-Type-Options, X-Frame-Options, Content-Security-Policy.
  • API Versioning: Use headers (e.g., Accept: application/vnd.example.v2+json) or URL paths (e.g., /api/v2/users) for API versioning.
  • Rate Limiting: Implement 429 Too Many Requests with a Retry-After header to prevent abuse.

Version Information

  • HTTP Protocol: HTTP/1.1 remains widely used. HTTP/2 and HTTP/3 (QUIC) are increasingly adopted for performance, but the core status codes and header concepts remain consistent. This cheatsheet applies to all versions.
  • CORS Specification: The CORS specification is stable and has been a W3C Recommendation since 2014. The principles and headers detailed here are current as of 2025-12-23.
  • Server/Framework Versions: Examples provided are based on common configurations for Express (Node.js), Nginx, and Apache, which are generally compatible with their latest stable versions.

References

  1. MDN Web Docs: HTTP
  2. MDN Web Docs: HTTP Status Codes
  3. MDN Web Docs: HTTP Headers
  4. MDN Web Docs: Cross-Origin Resource Sharing (CORS)
  5. W3C CORS Specification

Transparency Note

This cheatsheet was generated by an AI expert based on current knowledge and best practices for HTTP status codes, headers, and CORS configuration as of 2025-12-23. While efforts have been made to ensure accuracy and comprehensiveness, specific implementations may vary, and it’s always recommended to consult official documentation for the most precise and up-to-date information.