Creating a Server in Node.js | Lecture 5

 

Here are notes on creating a server in Node.js:


Creating a Server in Node.js

What is a Server in Node.js?

  • A server in Node.js listens for incoming requests and sends responses back to the client.
  • It uses the http module, which is built into Node.js.

Steps to Create a Basic Server

  1. Import the http Module:
    • Use the require() function to load the http module.
  2. Create the Server:
    • Use the http.createServer() method to create a new server instance.
    • Define a callback function to handle incoming requests and responses.
  3. Specify the Port and Start the Server:
    • Use the server.listen() method to start the server on a specific port.

Basic Example:

// Step 1: Import the http module

const http = require('http');

 

// Step 2: Create the server

const server = http.createServer((req, res) => {

    res.statusCode = 200; // Set HTTP status code

    res.setHeader('Content-Type', 'text/plain'); // Set response content type

    res.end('Hello, Node.js Server!'); // Send response

});

 

// Step 3: Start the server on port 3000

const PORT = 3000;

server.listen(PORT, () => {

    console.log(`Server is running at http://localhost:${PORT}/`);

});


Code Explanation

  1. http.createServer(callback):
    • Creates a server that listens for incoming HTTP requests.
    • The callback function has two parameters:
      • req: The request object.
      • res: The response object.
  2. res.statusCode:
    • Sets the HTTP status code for the response (e.g., 200 for success).
  3. res.setHeader(name, value):
    • Sets HTTP headers (e.g., Content-Type for specifying the type of response).
  4. res.end(data):
    • Ends the response and sends data to the client.
  5. server.listen(port, callback):
    • Starts the server on the specified port.
    • The callback runs once the server is ready.

Enhancements

1. Serve HTML Content:

const http = require('http');

 

const server = http.createServer((req, res) => {

    res.statusCode = 200;

    res.setHeader('Content-Type', 'text/html');

    res.end('<h1>Welcome to My Node.js Server</h1>');

});

 

server.listen(3000, () => {

    console.log('Server running at http://localhost:3000/');

});

2. Basic Routing:

const http = require('http');

 

const server = http.createServer((req, res) => {

    if (req.url === '/') {

        res.end('Welcome to the Home Page');

    } else if (req.url === '/about') {

        res.end('Welcome to the About Page');

    } else {

        res.statusCode = 404;

        res.end('404 Not Found');

    }

});

 

server.listen(3000, () => {

    console.log('Server running at http://localhost:3000/');

});

3. Serve JSON Data:

const http = require('http');

 

const server = http.createServer((req, res) => {

    res.statusCode = 200;

    res.setHeader('Content-Type', 'application/json');

    const data = { message: 'Hello, JSON!' };

    res.end(JSON.stringify(data));

});

 

server.listen(3000, () => {

    console.log('Server running at http://localhost:3000/');

});

4. Add Logging for Requests:

const http = require('http');

 

const server = http.createServer((req, res) => {

    console.log(`Received request: ${req.method} ${req.url}`);

    res.end('Request logged!');

});

 

server.listen(3000, () => {

    console.log('Server running at http://localhost:3000/');

});


Key Points to Remember

  1. Port Number:
    • Choose a port that is not in use (commonly 3000 or 8080 for development).
  2. Request Object (req):
    • Contains details of the client's request, such as method (GET, POST) and URL.
  3. Response Object (res):
    • Used to send data back to the client.
  4. Asynchronous Nature:
    • Node.js servers are non-blocking and can handle multiple requests simultaneously.

Let me know if you’d like to explore advanced topics, like integrating with frameworks (e.g., Express.js) or connecting to databases!

 

Comments

Popular posts from this blog

Introduction to Node.js | Lecture 1

Introduction to NPM | Lecture 2

Modules in Node.js | Lecture 4