0
0
Node.jsframework~5 mins

Creating a basic HTTP server in Node.js

Choose your learning style9 modes available
Introduction

We create an HTTP server to listen for requests from web browsers or other clients and send back responses like web pages or data.

You want to serve a simple web page from your computer.
You need to test how your website works locally before publishing.
You want to build a small API that other programs can talk to.
You want to learn how web servers work by making one yourself.
Syntax
Node.js
import http from 'http';

const server = http.createServer((req, res) => {
  // handle request and response here
});

server.listen(3000, () => {
  console.log(`Server running on port 3000`);
});

The http.createServer function creates a server that listens for requests.

The callback receives req (request) and res (response) objects to handle communication.

Examples
This server sends 'Hello World' to every request on port 3000.
Node.js
import http from 'http';

const server = http.createServer((req, res) => {
  res.end('Hello World');
});

server.listen(3000);
This server responds differently based on the URL path requested.
Node.js
import http from 'http';

const server = http.createServer((req, res) => {
  if (req.url === '/') {
    res.end('Home page');
  } else {
    res.statusCode = 404;
    res.end('Not found');
  }
});

server.listen(8080);
Sample Program

This program creates a simple HTTP server on port 4000. It sends a plain text message 'Welcome to my server!' for every request. When the server starts, it logs a message to the console.

Node.js
import http from 'http';

const port = 4000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Welcome to my server!');
});

server.listen(port, () => {
  console.log(`Server running on port ${port}`);
});
OutputSuccess
Important Notes

Always set the correct Content-Type header so browsers know how to display the response.

Use res.end() to finish the response and send data back to the client.

Remember to choose a port number that is free and allowed by your system.

Summary

Creating an HTTP server lets your computer respond to web requests.

Use http.createServer with a function to handle requests and responses.

Start the server with server.listen(port) and check the console for confirmation.