Welcome back to CodeYourCraft! Today, we're diving into a crucial aspect of Node.js - Headers and Status Codes. This lesson is designed for both beginners and intermediates, so let's get started! 📝
When a client (usually a web browser) sends a request to a server, the server responds with a response object. This response object contains important information about the server's response, including headers and status codes.
Headers are key-value pairs that provide additional information about the response. They can include details like the type of data being sent, cache control, and security information.
// Example of setting headers in Node.js
res.setHeader('Content-Type', 'text/html');
res.setHeader('Cache-Control', 'max-age=3600');Status codes are numbers that indicate the status of the server's response. They help the client understand the server's response quickly. The most common status codes are:
Let's take a closer look at some common status codes:
This is the most common status code. It indicates that the server has successfully completed the request.
This status code indicates that the requested resource could not be found on the server.
This status code indicates that something went wrong on the server, and the server could not complete the request.
Let's create a simple Node.js server that sends a response with a status code and headers.
const http = require('http');
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/html');
res.setHeader('Cache-Control', 'max-age=3600');
res.end('<h1>Hello, World!</h1>');
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});In this example, we create a simple HTTP server that responds with a status code of 200, sets the Content-Type and Cache-Control headers, and sends the HTML response <h1>Hello, World!</h1>.
What does the status code 200 OK indicate?
That's it for today! In the next lesson, we'll dive deeper into Node.js and learn more about request handling and middleware. Until then, happy coding! 💡