clientScript.js
This file will dispatch the petition to the Node server, and will handle the response, showing it on the screen.
The entire code will be contained by the "nodeRequest" function, called when the button from the client.html is clicked.
nodeRequest
At the beginning of the function we get the value from the input and we start a timer, to later calculate the time taken by the request.
nodeRequest = () => {
const t0 = performance.now();
const val = document.getElementById("input").value;
document.getElementById("input").innerHTML = "";
// Ajax Call to Node Server
}
Ajax petition
Then we have to issue the ajax call to our Node server, sending the value from the input
$.ajax({
url: "http://127.0.0.1:8000/" + val,
type: 'GET',
}).done((data) => {
// This code will execute when the node server responds and data will be the answer.
});
Ajax response
This code will handle the response from the server and will show it on screen on an User-friendly way (on a basic HTML table)
data = JSON.parse(data);
const table = document.getElementById("log");
const row = document.createElement("tr");
const Url = document.createElement("td");
Url.innerHTML = val;
const t1 = performance.now();
const ResponseTime = document.createElement("td");
ResponseTime.innerHTML = (t1 - t0) + " ms"; //Calculates the total response time
const Source = document.createElement("td");
if (data.from == "Redis"){
Source.setAttribute("class", "Redis");
} else {
Source.setAttribute("class", "Api");
}
Source.innerHTML = "<b>" + data.from + "</b>";
row.appendChild(Url);
row.appendChild(ResponseTime);
row.appendChild(Source);
table.appendChild(row);
Complete code
nodeRequest = () => {
const t0 = performance.now();
const val = document.getElementById("input").value;
document.getElementById("input").innerHTML = "";
$.ajax({
url: "http://127.0.0.1:8000/" + val,
type: 'GET',
}).done((data) => {
data = JSON.parse(data);
const table = document.getElementById("log");
const row = document.createElement("tr");
const Url = document.createElement("td");
Url.innerHTML = val;
const t1 = performance.now();
const ResponseTime = document.createElement("td");
ResponseTime.innerHTML = (t1 - t0) + " ms";
const Source = document.createElement("td");
if (data.from == "Redis"){
Source.setAttribute("class", "Redis");
} else {
Source.setAttribute("class", "Api");
}
Source.innerHTML = "<b>" + data.from + "</b>";
row.appendChild(Url);
row.appendChild(ResponseTime);
row.appendChild(Source);
table.appendChild(row);
});
}