How I built a http server that listens for requests at specific end points with just the http module of node js.

This is a break down of how I built a server using the http module and sent text, json and html as responses.

If you would follow along i expect you already have node installed if not check this tutorial on how to get started with node js or check the official documentation on node js and download the LTS version for your device.

Now lets get down to business.

First check if you have node on your device by typing node -v on your device terminal. mine currently is version 12.14.0

Screenshot (44).png

next we should create a file in desktop and name it httpServer.js

time to start coding πŸŽŠπŸŽ‡πŸŽ†

import http and create server

now open the newly created file in any editor of your choice and then import the http module from node like this

const http = require("http");

you might wonder why we require and not import the http module if you are new to node js. Well this is because node js uses the common js module for file imports. The http module has a method createServer that we use to turn our computer to a http server that listens to requests. Now let us create our server 😎and store it in a variable so we can use it later.

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

}));

the http.createServer method takes a callback function which is called at anytime we start our server.

now let us listen to requests sent to our server by inputting the code below under our server constant.

server.listen(4000, "localhost", () => {
  console.log(`server listening on port 4000`);
});

remember we saved our http.createServer method in a constant called server, well it has a method on it called listen that helps it listen for requests and it takes 3 parameters which are

1). a port ( a communication end point )

2). a host name ( a name for the port )

3). a callback function ( a function which is called every time we start our server )

our code should look like this now

const http = require("http");   

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

}));

server.listen(4000, "localhost", () => {
  console.log(`server listening on port 4000`);
});

Destructuring the url from the req parameter and sending a response to the user

the req parameter from our createServer method is an object that carries information about the request made to our server including the url.

we destructure the url from the req object like this :

const { url } = req;

now lets send a response based on the url sent in by the user

Sending a response for requests made to the "/text" endpoint

1). we check if the url is equal to /text

2). if it is, we set the status code to 200 ( meaning the request is ok )

3). we set the header's content-type to text/plain

4). we send a text response to the user via res.end

  if (url == "/text") {
    res.statusCode = 200;

    res.setHeader("Content-Type", "text/plain");
    res.end("it has been a pleasure creating this server");
  }

now our code should look like this

const http = require("http");   

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

const {url} = req;

if (url == "/text") {
    res.statusCode = 200;

    res.setHeader("Content-Type", "text/plain");
    res.end("it has been a pleasure creating this server");
  }
}));

server.listen(4000, "localhost", () => {
  console.log(`server listening on port 4000`);
});

Sending a response for requests made to the "/json" endpoint

1). we check if the url is equal to /json

2). if it is, we set the status code to 200 ( meaning the request is ok )

3). we set the header's content-type to application/json

4). we send a json response to the user via res.end p.s we can't send json as a response using res.end so we use the JSON.stringify method to convert to string so we can send the response.

 if (url == "/json") {
    res.statusCode = 200;

    res.setHeader("Content-Type", "application/json");
    res.end(
      JSON.stringify({ name: "Evans", hobby: "dancing", country: "Nigeria" })
    );
  }

now our code should look like this :

const http = require("http");   

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

const {url} = req;

if (url == "/text") {
    res.statusCode = 200;

    res.setHeader("Content-Type", "text/plain");
    res.end("it has been a pleasure creating this server");
  }
 if (url == "/json") {
    res.statusCode = 200;

    res.setHeader("Content-Type", "application/json");
    res.end(
      JSON.stringify({ name: "Evans", hobby: "dancing", country: "Nigeria" })
    );
  }
}));

server.listen(4000, "localhost", () => {
  console.log(`server listening on port 4000`);
});

Sending a response for requests made to the "/html" endpoint

1). we check if the url is equal to /html

2). if it is, we set the status code to 200 ( meaning the request is ok )

3). we set the header's content-type to text/html

4). we send a string response to the user containing html code via res.end

 if (url == "/html") {
    res.statusCode = 200;

    res.setHeader("Content-Type", "text/html");
    res.end(`
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1> hello mentor</h1>
</body>
</html>
`);
  }

Our final code should look like this :

const http = require("http");

const server = http.createServer((req, res) => {
  const { url } = req;
  if (url == "/text") {
    res.statusCode = 200;

    res.setHeader("Content-Type", "text/plain");
    res.end("it has been a pleasure creating this server");
  }
  if (url == "/json") {
    res.statusCode = 200;

    res.setHeader("Content-Type", "application/json");
    res.end(
      JSON.stringify({ name: "Evans", hobby: "dancing", country: "Nigeria" })
    );
  }
  if (url == "/html") {
    res.statusCode = 200;

    res.setHeader("Content-Type", "text/html");
    res.end(`
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1> hello mentor</h1>
</body>
</html>
`);
  }
});

server.listen(4000, "localhost", () => {
  console.log(`server listening on port 4000`);
});

Time to run our code

1) open your terminal and change the directory to that of the file

2) enter node httpServer.js on your terminal

Screenshot (45).png

if every thing is correct in your code you should get a message saying

server listening on port 4000

from our console.log method in the server.listen callback function

now open your browser and navigate to

1). http://localhost:4000/text to get the text response

1). http://localhost:4000/json to get the json response

1). http://localhost:4000/html to get the html response

I hope you have learnt a thing or two from this write up. if you have any questions please ask on.

Happy Coding 😁

Comments (2)

Chris Arter's photo

A great light-weight solution. Awesome write up!