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
| Concept | Description | Common Example / Syntax |
|---|---|---|
| HTTP Status | Server’s response to a client’s request, indicating success or failure. | 200 OK, 404 Not Found, 500 Internal Server Error |
| HTTP Header | Metadata sent with HTTP requests and responses. | Content-Type: application/json, Authorization: Bearer ... |
| CORS | Mechanism allowing web pages to request resources from a different domain. | Access-Control-Allow-Origin: https://example.com |
GET | Request data from a specified resource. | GET /users/123 |
POST | Submit data to be processed to a specified resource. | POST /users (with JSON body) |
PUT | Update a specified resource. | PUT /users/123 (with JSON body) |
DELETE | Delete a specified resource. | DELETE /users/123 |
OPTIONS | Describe 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.
| Code | Name | Description | Example Use Case |
|---|---|---|---|
100 | Continue | Client should continue with its request. | Sent by server to client after receiving request headers, prompting client to send request body. |
101 | Switching Protocols | Server 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.
| Code | Name | Description | Example Use Case |
|---|---|---|---|
200 | OK | Standard response for successful HTTP requests. | Successful GET, PUT, PATCH, DELETE requests. |
201 | Created | Request has been fulfilled and a new resource created. | Successful POST request creating a new user or resource. |
202 | Accepted | Request accepted for processing, but not yet completed. | Asynchronous processing where the request will eventually be fulfilled. |
204 | No Content | Server 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.
| Code | Name | Description | Example Use Case |
|---|---|---|---|
301 | Moved Permanently | Resource has been permanently moved to a new URL. | Old URL redirects to a new, permanent URL for a resource. |
302 | Found (formerly Moved Temporarily) | Resource has been temporarily moved to a new URL. | Redirecting a user to a login page after session expiration. |
304 | Not Modified | Resource 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.
| Code | Name | Description | Example Use Case |
|---|---|---|---|
400 | Bad Request | Server cannot process the request due to client error (e.g., malformed syntax). | Invalid JSON payload, missing required parameters. |
401 | Unauthorized | Request requires user authentication. | Accessing a protected resource without a valid authentication token. |
403 | Forbidden | Server understood the request but refuses to authorize it. | User is authenticated but lacks necessary permissions for the resource. |
404 | Not Found | Server cannot find the requested resource. | Requesting a non-existent API endpoint or resource ID. |
405 | Method Not Allowed | Request 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. |
409 | Conflict | Request conflicts with the current state of the target resource. | Trying to create a resource that already exists (e.g., duplicate username). |
429 | Too Many Requests | User 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.
| Code | Name | Description | Example Use Case |
|---|---|---|---|
500 | Internal Server Error | Generic error message when an unexpected condition was encountered. | Unhandled exception in the server application logic. |
502 | Bad Gateway | Server acting as a gateway/proxy received an invalid response from an upstream server. | Backend service is down or unresponsive behind a proxy. |
503 | Service Unavailable | Server 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. |
504 | Gateway Timeout | Server 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.
| Header | Description | Example |
|---|---|---|
Cache-Control | Directives for caching mechanisms. | Cache-Control: no-cache, max-age=3600 |
Connection | Control whether the network connection stays open after the current transaction. | Connection: keep-alive |
Date | The date and time at which the message was originated. | Date: Tue, 15 Nov 2025 08:12:31 GMT |
Transfer-Encoding | Encoding applied to the payload body. | Transfer-Encoding: chunked |
Request Headers
Specific to client requests.
| Header | Description | Example |
|---|---|---|
Accept | Media types that are acceptable for the response. | Accept: application/json, text/plain |
Accept-Encoding | Content encodings that are acceptable for the response. | Accept-Encoding: gzip, deflate |
Authorization | Credentials for authenticating a user agent with a server. | Authorization: Bearer <token> |
Content-Type | Media type of the resource in the request body. | Content-Type: application/json |
Host | Domain name of the server (for virtual hosting). | Host: api.example.com |
User-Agent | Information about the user agent (browser, client). | User-Agent: Mozilla/5.0 (...) Chrome/... |
Referer | Address of the previous web page from which a link was followed. | Referer: https://www.example.com/page |
Origin | Indicates the origin of the cross-origin request (for CORS). | Origin: https://client.example.com |
Response Headers
Specific to server responses.
| Header | Description | Example |
|---|---|---|
Content-Type | Media type of the resource in the response body. | Content-Type: application/json; charset=utf-8 |
Content-Length | Size of the resource body, in bytes. | Content-Length: 1024 |
ETag | An identifier for a specific version of a resource. | ETag: "abcdef123" |
Location | Used in redirection (3xx) or resource creation (201) to indicate the new URL. | Location: /new-resource/123 |
Server | Information about the software used by the origin server. | Server: Nginx/1.25.3 |
Set-Cookie | Sends cookies from the server to the user agent. | Set-Cookie: sessionid=abc; HttpOnly; Secure |
WWW-Authenticate | Defines the authentication method that should be used to gain access to a resource. | WWW-Authenticate: Basic realm="Access to API" |
Allow | List of HTTP methods supported by a resource. | Allow: GET, HEAD, OPTIONS |
CORS-Related Headers
Used for Cross-Origin Resource Sharing.
| Header | Description | Example |
|---|---|---|
Access-Control-Allow-Origin | Indicates 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-Methods | Indicates the HTTP methods allowed when accessing the resource. | Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS |
Access-Control-Allow-Headers | Indicates which HTTP headers can be used when making the actual request. | Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With |
Access-Control-Expose-Headers | Indicates which headers can be exposed as part of the response by listing their names. | Access-Control-Expose-Headers: X-Custom-Header |
Access-Control-Max-Age | Indicates how long the results of a preflight request can be cached. | Access-Control-Max-Age: 86400 (24 hours) |
Access-Control-Allow-Credentials | Indicates 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:8080is a different origin fromhttp://example.com:8080orhttps://sub.example.com. - Simple Request: A request that meets certain criteria (e.g.,
GET,HEAD,POSTwith specificContent-Typeheaders). These requests are sent directly, and the browser checks theAccess-Control-Allow-Originheader in the response. - Preflight Request: For “non-simple” requests (e.g.,
PUT,DELETE,PATCH, orPOSTwithContent-Type: application/json), the browser first sends anOPTIONSrequest to the server. This “preflight” asks the server for permission to send the actual request. The server must respond with appropriateAccess-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
500for all errors. Be precise with4xxand5xxcodes to give clients meaningful feedback. - Idempotency:
GET,PUT,DELETE, andHEADmethods should be idempotent, meaning making the same request multiple times has the same effect as making it once.POSTis generally not idempotent. - CORS Debugging:
- Check browser developer tools (Network tab) for
OPTIONSrequests and their responses. - Look for
CORSerrors in the browser console. - Use
curl -v -H "Origin: https://bad.origin.com" -X OPTIONS http://your-api.com/resourceto simulate preflight requests.
- Check browser developer tools (Network tab) for
- 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 Requestswith aRetry-Afterheader 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
- MDN Web Docs: HTTP
- MDN Web Docs: HTTP Status Codes
- MDN Web Docs: HTTP Headers
- MDN Web Docs: Cross-Origin Resource Sharing (CORS)
- 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.