Postman Clone - Project


This project will help you learn GET and POST method along with JSON structuring. 

index.html:
---------------

<!DOCTYPE html>
<html lang="en">
<head>
    <!-- Required meta tags -->
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"
        integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous" />
        <link rel="stylesheet" href="prism.css">
        <style>
            #responsePrismPre{
                max-height: 500px;
                /* max-width: 500px; */
            }
        </style>
    <title>Postman CLone</title>
</head>
<body>
    <!-- navbar -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
        <a class="navbar-brand" href="#">Postmaster - A Postman Clone</a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>

        <div class="collapse navbar-collapse" id="navbarSupportedContent">
            <ul class="navbar-nav mr-auto">
                <li class="nav-item active">
                    <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#">About Us</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#">Contact Us</a>
                </li>
            </ul>
            <form class="form-inline my-2 my-lg-0">
                <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search" />
                <button class="btn btn-outline-success my-2 my-sm-0" type="submit">
                    Search
                </button>
            </form>
        </div>
    </nav>

    <div class="container">
        <h1 class="my-3">Welcome to Postmaster</h1>
    </div>

    <!-- url input -->
    <div class="container">
        <div class="form-group row">
            <label for="url" class="col-sm-2 col-form-label">URL</label>
            <div class="col-sm-10">
                <input type="text" class="form-control" id="urlField" placeholder="enter url here" />
            </div>

        </div>

        <!-- request type radio -->
        <fieldset class="form-group">
            <div class="row">
                <legend class="col-form-label col-sm-2 pt-0">Request Type</legend>
                <div class="col-sm-10">
                    <div class="form-check">
                        <input class="form-check-input" type="radio" name="requestType" id="get" value="GET" checked />
                        <label class="form-check-label" for="get">
                            GET
                        </label>
                    </div>
                    <div class="form-check">
                        <input class="form-check-input" type="radio" name="requestType" id="post" value="POST" />
                        <label class="form-check-label" for="post">
                            POST
                        </label>
                    </div>
                </div>
            </div>
        </fieldset>

        <!-- content type radio -->
        <fieldset class="form-group">
            <div class="row">
                <legend class="col-form-label col-sm-2 pt-0">Content Type</legend>
                <div class="col-sm-10">
                    <div class="form-check">
                        <input class="form-check-input" type="radio" name="contentType" id="jsonRadio" value="json"
                            checked />
                        <label class="form-check-label" for="json">
                            JSON
                        </label>
                    </div>
                    <div class="form-check">
                        <input class="form-check-input" type="radio" name="contentType" id="paramsRadio"
                            value="params" />
                        <label class="form-check-label" for="params">
                            Custom Parameters
                        </label>
                    </div>
                </div>
            </div>
        </fieldset>

        <!-- parameters box : this will hide when Json radio is choosen and vice versa-->
        <div id="parametersBox" class = "my-3">
            <div class="form-row">
                <label for="inputEmail4" class="col-sm-2 col-form-label">Parameter 1</label>
                <div class="col-md-4">
                    <input type="text" class="form-control" id="parameterKey1" placeholder="Enter parameter key 1" />
                </div>
                <div class="col-md-4">
                    <input type="text" class="form-control" id="parameterValue1" placeholder="Enter parameter value 1" />
                </div>
                <button class="btn btn-primary" id="addMoreParam">+</button>
            </div>
        

        <div id="params">
                <!-- dynamically by js -->
        </div>
        </div>

        <!-- json request box : this will hide when coustom parameter radio -->
        <div id="requestJsonBox" class="my-3">
            <div class="form-group row" >
                <label for="requestJsonBox" class="col-sm-2 col-form-label">Request json here</label>
                <div class="col-sm-10">
                    <textarea class="form-control" id="requestJsonText" rows="3" placeholder="Request here"></textarea>
                </div>
            </div>
        </div>

        <!-- submit button which will fetch api -->
        <div class="form-group row">
            <div class="col-sm-10">
                <button id="submit" class="btn btn-primary">Submit</button>
            </div>
        </div>

        <!-- response box -->
        <div class="form-group row my-3" id="responseJsonBox">
            <label for="responseJsonBox" class="col-sm-2 col-form-label">Response here</label>
            <div class="col-sm-10">
                <!-- <textarea class="form-control" id="responseJsonText" rows="3" placeholder="Response here"></textarea> -->
                <pre id="responsePrismPre" class="language-javascript">
                    <code id="responseJsonText" class="language-javascript" >

                    </code>
                </pre>
            </div>
        </div>

    </div>

    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
        integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
        crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"
        integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo"
        crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"
        integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI"
        crossorigin="anonymous"></script>

    <script src="index.js"></script>
    <script src="prism.js"></script>
</body>
</html>


index.js:
------------
console.log("the postmaster");

let parametersBox = document.getElementById("parametersBox");

// hiding parameter box initialially as json radio is choosen.
document.getElementById("parametersBox").style.display = "none";

// initializing no. of parameter box
let addedParamsCount = 0;

// url box validation
let urlField = document.getElementById("urlField");
urlField.addEventListener("blur", () => {
  // let regex = /^[a-z]([0-9a-zA-Z]){1,30}$/;
  let regex = /^(ftp|http|https):\/\/[^ "]+$/;
  let str = urlField.value;
  console.log(regex, str);

  if (regex.test(str)) {
    console.log("it matched");
    urlField.classList.add("is-valid");
    urlField.classList.remove("is-invalid");
    // validName = true;
  } else {
    console.log("not matched");
    urlField.classList.add("is-invalid");
    urlField.classList.remove("is-valid");
    // validName = false;
  }
});

// function to get dom element from string
function getElementFromString(string) {
  let div = document.createElement("div");
  div.innerHTML = string;
  // console.log("div.innerHTML..",div.innerHTML);
  // console.log("div.firstElementChild", div.firstElementChild);
  return div.firstElementChild;
}

// if user clicks on json then hiding params box
let jsonRadio = document.getElementById("jsonRadio");
jsonRadio.addEventListener("click", () => {
  document.getElementById("parametersBox").style.display = "none";
  document.getElementById("requestJsonBox").style.display = "block";
  // console.log("clicked jsonradio");
});

// if user clicks on params(cusotm parameter) then hiding json
let paramsRadio = document.getElementById("paramsRadio");
paramsRadio.addEventListener("click", () => {
  document.getElementById("requestJsonBox").style.display = "none";
  document.getElementById("parametersBox").style.display = "block";
  // console.log("clicked paramsradio");
});

// if the user clicks on + btn , add more parameter

let addMoreParamBtn = document.getElementById("addMoreParam");
let params = document.getElementById("params");

addMoreParamBtn.addEventListener("click", () => {
  let string = `
    <div class="form-row my-3">
      <label for="inputEmail4" class="col-sm-2 col-form-label">Parameter ${
    addedParamsCount + 2
    }</label>
          <div class="col-md-4">
              <input type="text" class="form-control" id="parameterKey${
    addedParamsCount + 2
    }" placeholder="Enter parameter key ${addedParamsCount + 2}"/>
          </div>
          <div class="col-md-4">
              <input type="text" class="form-control" id="parameterValue${
    addedParamsCount + 2
    }" placeholder="Enter parameter value ${addedParamsCount + 2}" />
          </div>
              <button class="btn btn-primary deleteParam" id="addMoreParam">-</button>
    </div>
            `;

  // convert the element string to DOM node
  paramElement = getElementFromString(string);
  params.appendChild(paramElement);

  // adding event listener to remove the parameter box on clicking '-' button
  let deleteParam = document.getElementsByClassName("deleteParam");
  for (item of deleteParam) {
    item.addEventListener("click", (e) => {
      // confirm("Are you sure you want to delete?");
      e.target.parentElement.remove();
    });
  }
  addedParamsCount++;
});

// if user clicks on submit button
let submit = document.getElementById("submit");
submit.addEventListener("click", () => {

  // fething all the values i.e URl , contentType , requestType
  let urlField = document.getElementById("urlField").value;

  console.log("urlFiled on submit", urlField);
  if (urlField == "") {
    alert("please enter URL");
  } else {
    var requestType = document.querySelector( 'input[name = "requestType"]:checked' ).value;
    var contentType = document.querySelector( 'input[name = "contentType"]:checked' ).value;
    document.getElementById("responseJsonText").innerHTML = "Please Wait...Fetching your response...";
  }
  console.log(urlField, requestType, contentType);
  
  // storing all parameter values if user enter throught parameter(on POST request)
  if (contentType == "params") {
    data = {};
    for (i = 0; i < addedParamsCount + 1; i++) {
      if (document.getElementById(`parameterKey${i + 1}`) != undefined) {
        let key = document.getElementById(`parameterKey${i + 1}`).value;
        let value = document.getElementById(`parameterValue${i + 1}`).value;
        data[key] = value;
      }
    }
    data = JSON.stringify(data)
  } else {
    // data = JSON.parse(document.getElementById("requestJsonText").value);
    data = document.getElementById("requestJsonText").innerHTML;
    console.log("data if not parameterizes",data);
    // data = JSON.parse(data);
  }

  // if request type is "GET" , invoke fetch api
  if (requestType == "GET") {
    fetch(urlField, { method: "GET" })
      .then((response) => {
        return response.text();
      })
      .then((text) => {
        
        // document.getElementById("responseJsonText").value = text;
        document.getElementById("responseJsonText").innerHTML = text;
        Prism.highlightAll();
      });
  } 
  else
  //if request type is "POST"
   {
    params1 = {
      method: "POST",
      headers: {
        "Content-type": "application/json; charset=UTF-8",
      },
      body: data,
    };
    fetch(urlField, params1)
      .then((response) => {
        return response.text();
      })
      .then((text) => {
        document.getElementById("responseJsonText").innerHTML = text;
        // JSON.parse(document.getElementById("responseJsonText").value) = text;
        Prism.highlightAll();
      });
  }

  console.log(data);
});

(Adding Prism is just for styling purposes. It is optional for you but I would recommend it because it will really make your website attractive)

Download: Prism js and Prism css from here and save with the name prism.js and prism.css respectively.

Add both the file to the same folder where you have place index.html and index.js and your code will run just fine.


0 Comments