Welcome to our in-depth Node.js tutorial on Status Codes! We'll explore the world of HTTP response status codes, an essential part of every web developer's toolkit. Let's dive in! 🏊♂️
HTTP status codes are three-digit numbers returned by a server in response to a client's (like a browser or an application) request. They provide information about the success or failure of the request.
Understanding status codes helps you debug issues, improve user experience, and ensure the correct functionality of your web applications.
Status codes are categorized into five classes based on the first digit:
Let's look at some commonly encountered status codes from each class.
100 Continue: The client should continue with the request without additional data.200 OK: The request has succeeded. The server's response contains the desired data.201 Created: The request has been fulfilled and resulted in a new resource being created.301 Moved Permanently: The requested resource has been permanently moved to a new URL.304 Not Modified: The server has not modified the resource since the client last accessed it, so the browser can display the local cached version.400 Bad Request: The client's request is malformed or contains invalid data.401 Unauthorized: The client needs to authenticate to get the requested resource.404 Not Found: The requested resource could not be found on the server.500 Internal Server Error: The server encountered an unexpected condition and couldn't fulfill the request.503 Service Unavailable: The server is temporarily unable to handle the request due to maintenance or overloaded resources.What is the meaning of the status code 503?
Let's create a simple Node.js server that responds with different status codes:
const http = require('http');
const server = http.createServer((req, res) => {
switch (req.url) {
case '/':
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Welcome to CodeYourCraft!');
break;
case '/notfound':
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Oops! Resource not found.');
break;
case '/error':
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Something went wrong!');
break;
default:
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Resource not found.');
}
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000');
});Start this server and visit http://localhost:3000, http://localhost:3000/notfound, and http://localhost:3000/error in your browser to see different status codes in action!
With this newfound knowledge, you're well on your way to mastering HTTP status codes! Keep exploring the wonderful world of Node.js and happy coding! 🎯🎉