nodejs logo

Creating an HTTP Server in Node.js

Overview

Node.js provides a built-in module called http that allows you to create an HTTP server. This server can handle requests and send responses to clients.

Creating a Basic HTTP Server

Here's how to create a simple HTTP server:

const http = require('http');

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

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

In this example, the server responds with "Hello, World!" to any request it receives.

Handling Different Routes

Here's how to handle different routes in your server:

const http = require('http');

const server = http.createServer((req, res) => {
  if (req.url === '/') {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');
    res.end('Home Page');
  } else if (req.url === '/about') {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');
    res.end('About Page');
  } else {
    res.statusCode = 404;
    res.setHeader('Content-Type', 'text/plain');
    res.end('Page Not Found');
  }
});

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

This server checks the URL of incoming requests and responds accordingly.

Sending JSON Responses

You can also send JSON responses by setting the appropriate content type:

const http = require('http');

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'application/json');
  const responseData = { message: 'Hello, World!', success: true };
  res.end(JSON.stringify(responseData)); // Send JSON response
});

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

This example demonstrates how to send a JSON response instead of plain text.

© 2024 Node.js HTTP Server Guide