GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Home
  • ES6
  • Web
  • JS BOM
  • JS DOM
  • Web API
  • React
  • Node.js
  • Express
  • React Native
  • JavaScript Array Methods
  • JavaScript String Methods
  • Regular Expressions
  • ES Next

This view

  • Original page
  • New address

GeezerVison is showing www.javascripttutorial.net — How to Use Node.js HTTP Module to Create a Simple HTTP Server.

Home » Node.js Tutorial » Node.js HTTP Module

Summary: in this tutorial, you will learn about the Node.js http module and how to use it to create a simple HTTP server.

Introduction to the Node.js HTTP module #

The http module is a core module of Node designed to support many features of the HTTP protocol.

The following example shows how to use the http module:

First, create a new file called server.js and include the http module by using the require() function:

const http = require('http');

Second, create an HTTP server using the createServer() method of the http object.

const server = http.createServer((req, res) => {
    if (req.url === '/') {
        res.write('<h1>Hello, Node.js!</h1>');
    }
    res.end();
});

The createServer() accepts a callback that has two parameters: HTTP request (req) and response (res). Inside the callback, we send an HTML string to the browser if the URL is / and end the request.

Third, listen to the incoming HTTP request on the port 5000:

server.listen(5000);
console.log(`The HTTP Server is running on port 5000`);

Put it all together:

const http = require('http');

const server = http.createServer((req, res) => {
    if (req.url === '/') {
        res.write('<h1>Hello, Node.js!</h1>');
    }
    res.end();
});

server.listen(5000);
console.log(`The HTTP Server is running on port 5000`);

The following starts the HTTP server:

node server.js

Output:

The HTTP Server is running on port 5000

Now, you can launch the web browser and go to the URL http://localhost:5000/. You’ll see the following message:

Hello, Node.js

This simple example illustrates how to use the http module. In practice, you will not use the http module directly. Instead, you will use a popular module called express to handle HTTP requests and responses.

Was this helpful?

Thank you for your feedback!

You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.