The following code pings an NGINX location block on my NGINX server to give you a health check status.
const ping = async () => {
const url = `http://10.10.1.100/status`;
const postData = {
method: 'POST', // *GET, POST, PATCH, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
headers: {
'Content-Type': 'text/plain; charset=ASCII'
},
body: 'PING'
}
try {
let factor = 1;
let timeout = 3000; // ms
let start = (new Date()).getTime();
const request = await fetch(url, postData);
let delta = new Date().getTime() - start;
delta *= (factor || 1);
if(delta > timeout) throw new Error(`PONG > ${timeout}ms. Server down?`);
if(!request.ok) throw new Error(`${request.status} ${request.statusText}`);
const response = await request.text();
if(!response) throw new Error(`${response}`);
document.getElementById('serverPongSpeed').innerText = `${delta.toFixed(0)}ms`;
// Do Something...
console.log(`%c${delta.toFixed(0)}ms ${response}`, "color: #c6ff00"); // Lime A400
} catch (error) {
console.log(error);
}
}
The NGINX location block:
location = /status {
access_log off;
default_type text/plain;
add_header "Access-Control-Allow-Methods" "POST";
add_header "Content-Type" "text/plain";
return 200 "PONG";
}
Right now I run it like this:
setInterval(ping, 3000); // Every 3 seconds
The problem is, during testing, when I turn off NGINX to see what happens the PING doesn’t break. It just keeps sending POST requests.
Maybe it’s an error I am not catching? Or maybe there is no error because the fetch has a greater timeout? Maybe setting a fetch timeout at 3 seconds would fire something for me to catch..
2
Answers
Below is a revised, complete example of the desired working solution.
The javascript asynch await ping function:
...
...
The NGINX server /status location block:
/location
end point....
you can use ClearInterval() method like this:
you need some more code to count the time outs/ errors.
something like circuit breaker pattern