In this section, we will learn how to create a simple HTTP server using Node.js. This is a fundamental skill for any Node.js developer, as it forms the basis for building web applications and APIs.

Key Concepts

  1. HTTP Module: Node.js has a built-in module called http that allows you to create an HTTP server.
  2. Server Object: The http.createServer() method creates an HTTP server object.
  3. Request and Response: The server object listens for HTTP requests and sends back responses.

Step-by-Step Guide

  1. Import the HTTP Module

First, you need to import the http module. This module provides the functionality to create an HTTP server.

const http = require('http');

  1. Create the Server

Use the http.createServer() method to create a server. This method takes a callback function as an argument. The callback function is executed each time the server receives a request.

const server = http.createServer((req, res) => {
    // Handle the request and send a response
});

  1. Handle Requests and Send Responses

Inside the callback function, you can handle the incoming request (req) and send a response (res). For this example, we will send a simple "Hello, World!" message.

const server = http.createServer((req, res) => {
    res.statusCode = 200; // HTTP status code 200: OK
    res.setHeader('Content-Type', 'text/plain'); // Set the content type to plain text
    res.end('Hello, World!\n'); // Send the response body
});

  1. Listen on a Port

Finally, you need to specify the port on which the server should listen for incoming requests. Common practice is to use port 3000 for development.

const PORT = 3000;
server.listen(PORT, () => {
    console.log(`Server running at http://localhost:${PORT}/`);
});

Complete Code Example

Here is the complete code to create a simple HTTP server:

const http = require('http');

const server = http.createServer((req, res) => {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');
    res.end('Hello, World!\n');
});

const PORT = 3000;
server.listen(PORT, () => {
    console.log(`Server running at http://localhost:${PORT}/`);
});

Running the Server

  1. Save the code in a file named server.js.
  2. Open your terminal and navigate to the directory where server.js is located.
  3. Run the server using the following command:
node server.js
  1. Open your web browser and go to http://localhost:3000. You should see the message "Hello, World!".

Practical Exercise

Exercise 1: Modify the Response

Modify the server to send an HTML response instead of plain text.

Solution

const http = require('http');

const server = http.createServer((req, res) => {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/html');
    res.end('<h1>Hello, World!</h1>');
});

const PORT = 3000;
server.listen(PORT, () => {
    console.log(`Server running at http://localhost:${PORT}/`);
});

Exercise 2: Add Routing

Modify the server to handle different routes. For example, respond with "Welcome to the Home Page" for the root URL (/) and "About Us" for the /about URL.

Solution

const http = require('http');

const server = http.createServer((req, res) => {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/html');

    if (req.url === '/') {
        res.end('<h1>Welcome to the Home Page</h1>');
    } else if (req.url === '/about') {
        res.end('<h1>About Us</h1>');
    } else {
        res.statusCode = 404;
        res.end('<h1>404 Not Found</h1>');
    }
});

const PORT = 3000;
server.listen(PORT, () => {
    console.log(`Server running at http://localhost:${PORT}/`);
});

Common Mistakes and Tips

  • Forgetting to set the Content-Type header: Always set the appropriate Content-Type header to inform the client about the type of content being sent.
  • Not handling different routes: Make sure to handle different routes and provide appropriate responses for each.
  • Not closing the response: Always call res.end() to close the response and send it to the client.

Conclusion

In this section, you learned how to create a simple HTTP server using Node.js. You now know how to handle requests, send responses, and implement basic routing. This foundational knowledge will be crucial as you move on to more advanced topics in Node.js.

Node.js Course

Module 1: Introduction to Node.js

Module 2: Core Concepts

Module 3: File System and I/O

Module 4: HTTP and Web Servers

Module 5: NPM and Package Management

Module 6: Express.js Framework

Module 7: Databases and ORMs

Module 8: Authentication and Authorization

Module 9: Testing and Debugging

Module 10: Advanced Topics

Module 11: Deployment and DevOps

Module 12: Real-World Projects

© Copyright 2024. All rights reserved