HTTP Status Codes: A Comprehensive Analysis of the ‘Morse Code’ Sent by the Server

Introduction

HTTP Status Codes: A Comprehensive Analysis of the 'Morse Code' Sent by the Server

【Preface】

Long time no see! I have been busy with the launch of a new project for the past six months, and I haven’t written an article in a while (please be gentle πŸ˜…). During this time, while troubleshooting online issues, I found that many colleagues still understand HTTP status codes as just “200=Success, 404=Not Found”…

Until last week, intern Xiao Zhang spent a long time studying the 401 error code and finally came to ask me: “Does this unauthorized error mean the server crashed?”

Today, we will use real development scenarios to discuss the secrets behind these three-digit codes. I guarantee that after reading this, seeing them again will feel like reuniting with an old friend!

πŸ” 1xx: The Server Says ‘Busy, Please Don’t Rush’

These status codes are like the “Order Accepted” notification from a food delivery service:

// My file upload progress monitoringconst xhr = new XMLHttpRequest();xhr.upload.onprogress = (e) => {    if (e.lengthComputable) {        console.log(`Upload progress: ${(e.loaded / e.total) * 100}%`);    }};// The underlying layer may trigger 100 Continue

Common Status Codes:

  • 🟑 100 Continue: “Request headers received, please continue sending the body”
  • 🟑 102 Processing: “Processing, please do not close the connection” (commonly used in WebDAV)

βœ… 2xx: Success! But Don’t Celebrate Too Early

🟒 200 OK (Standard Success)

const getUser = async () => {    const response = await fetch('/api/user/me');    if (response.status === 200) {        const data = await response.json();        if (!data.name) {            throw new Error("The server says it's successful, but didn't give me a name!");        }    }};

🟒 204 No Content (Success but No Return)

const clearCart = async () => {    const res = await fetch('/api/cart/me', { method: 'DELETE' });    if (res.status === 204) {        alert('The cart has been cleared!'); // But res.json() will throw an error!    }};

🟒 206 Partial Content (Chunked Download)

// My video segmented requestfetch('/big-video.mp4', {    headers: { 'Range': 'bytes=0-999999' }});

πŸ”€ 3xx: Redirection? Beware of Loops!

πŸ”΅ 301 Moved Permanently (Moved Permanently)

fetch('/old-api')    .then(res => {        console.log(res.url); // The actual request is to the new address    });

πŸ”΅ 302 Found (Temporary Redirect)

// Assuming not logged in accessing /profilefetch('/profile');// Returns 302 redirect to /login?redirect=/profile

⚠️ Pitfall: 302 is used for temporary redirection in this application, but some older systems misuse it as a permanent redirect

❌ 4xx: It’s Your Problem, Don’t Shift Blame to the Backend!

πŸ”΄ 400 Bad Request (Parameter Error)

fetch('/api/order', {    method: 'POST',    body: JSON.stringify({ drink: 'milk tea' }) // Missing sugarLevel!});

πŸ”΄ 401 Unauthorized (Unauthorized)

fetch('/api/admin', {    headers: { 'Authorization': '' } // Where's the token?!});

πŸ”΄ 403 Forbidden (Insufficient Permissions)

fetch('/api/super-admin'); // Regular admin accessing super admin interface

πŸ”΄ 404 Not Found (Resource Not Found)

fetch('/api/products/nonexistentID') 404 Not Found (Resource Not Found)

πŸ’₯ 5xx: Backend: It’s My Fault!

🟠 500 Internal Server Error (Server Crashed)

fetch('/api/order', { method: 'POST' });// Returns: {"error":"Database connection timeout"}

🟠 502 Bad Gateway (Gateway Down)

fetch('/api');// Returns: nginx 502 error page

🟠 504 Gateway Timeout (Gateway Timeout)

fetch('/api/slow-query', { timeout: 5000 });

πŸ› οΈ Practical Tips: Elegant Error Handling

1. Axios Global Interceptor

axios.interceptors.response.use(    response => response,    error => {        const status = error.response?.status;        if (status === 401) {            router.push('/login');        } else if (status === 429) {            alert('You are clicking too fast, slow down!');        }        return Promise.reject(error);    });

2. Friendly Error Messages

const errorMessages = {    400: 'Parameter error, please check your input',    403: 'Insufficient permissions, please contact the administrator',    500: 'The server is having issues, please try again later'};alert(errorMessages[status] || 'Unknown error');

πŸ“ Conclusion

Recently, while training newcomers, I found that many colleagues panic when they see 4xx/5xx. In fact, status codes are like the Morse code sent by the server, and once deciphered, they can quickly help locate the problem.

Mnemonic:

  • βœ… 2xx: Success but data needs verification
  • πŸ”€ 3xx: Redirects beware of infinite loops
  • ❌ 4xx: Client-side issues, don’t shift blame
  • πŸ’₯ 5xx: Server-side issues, call for help

This article’s examples are from real projects (sensitive information has been anonymized). If you find it helpful, feel free to like/share for support~ ✨“`

HTTP Status Codes: A Comprehensive Analysis of the 'Morse Code' Sent by the Server

WeChat Official Account: Full Stack Xiao Yang

WeChat ID: y_t_t_t_

Scan to follow for more information

HTTP Status Codes: A Comprehensive Analysis of the 'Morse Code' Sent by the ServerHTTP Status Codes: A Comprehensive Analysis of the 'Morse Code' Sent by the ServerHTTP Status Codes: A Comprehensive Analysis of the 'Morse Code' Sent by the ServerHTTP Status Codes: A Comprehensive Analysis of the 'Morse Code' Sent by the ServerHTTP Status Codes: A Comprehensive Analysis of the 'Morse Code' Sent by the Server

Click ‘View’ if you find this helpful

Leave a Comment