Node.js Tutorial: Headers and Status Codes 🎯

beginner
24 min

Node.js Tutorial: Headers and Status Codes 🎯

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! 📝

What are Headers and Status Codes? 💡

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

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.

javascript
// Example of setting headers in Node.js res.setHeader('Content-Type', 'text/html'); res.setHeader('Cache-Control', 'max-age=3600');

Status Codes

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:

  • 2xx: Successful response
  • 3xx: Redirect
  • 4xx: Client error
  • 5xx: Server error

Understanding Status Codes 💡

Let's take a closer look at some common status codes:

200 OK

This is the most common status code. It indicates that the server has successfully completed the request.

404 Not Found

This status code indicates that the requested resource could not be found on the server.

500 Internal Server Error

This status code indicates that something went wrong on the server, and the server could not complete the request.

Practical Example 💡

Let's create a simple Node.js server that sends a response with a status code and headers.

javascript
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>.

Quiz Time 💡

Quick Quiz
Question 1 of 1

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! 💡