Understanding Node.js Server Communication

Aug 11, 2024

Node.js Server Communication

Introduction

  • Server-side code powered by Node.js and JavaScript.
  • Creates a website that listens for incoming requests from a browser.

The Process of Communication

  • Request Initiation:
    • Type a website address in a browser and hit enter.
    • This sends a request to the server powering that website.
  • Server Response:
    • The server processes the request and sends back a response (typically an HTML page).
    • Can also send images, CSS, JSON, etc.

IP Addresses and Domains

  • IP Addresses:
    • Unique addresses identifying computers on the Internet.
    • Hosts have IP addresses hosting websites.
  • Domain Names:
    • Mask IP addresses for easier access.
    • When a domain name is typed into a browser, it resolves to the associated IP address.

Types of Requests

  • GET Requests:
    • Made automatically when navigating to a webpage or clicking links.
  • POST Requests:
    • Used to send data to servers (e.g., submitting forms).
  • HTTP Protocol:
    • Stands for Hypertext Transfer Protocol.
    • A set of instructions for communication between clients (browsers) and servers.

Creating a Server with Node.js

  • Server is manually created in Node.js using the http module.
  • Server Creation Steps:
    1. Require the HTTP module:
      const http = require('http');
      
    2. Create the server using http.createServer(), which accepts a callback function to handle requests.
    3. The callback function provides:
      • Request Object: Contains information about the request (e.g., URL, request type).
      • Response Object: Used to send a response back to the browser.
    4. Log message to console upon receiving requests:
      console.log('Request made');
      
  • Listening for Requests:
    • Use server.listen(port, hostname, callback):
      • Example: server.listen(3000, 'localhost', () => { console.log('Listening on port 3000'); });
    • Localhost:
      • Refers to the loopback IP address (127.0.0.1), connecting to your own computer.
    • Port Numbers:
      • Represents specific channels for software communication.
      • Commonly used port number for local development is 3000.

Running the Server

  • Run the server file using Node.js:
    node server.js
    
  • The server will now listen for requests at localhost:3000.
  • Press Ctrl + C to stop the server.

Testing the Server

  • Open a browser and navigate to http://localhost:3000.
  • The request will be logged in the terminal, but no response will be sent yet.

Sending Responses to the Browser

  • The next lesson will cover how to use the response object to send data back to the browser.