简体   繁体   中英

How to show health status of node server on HTML

I have two servers. One is server1 running on port 8080 and another one is main app server which is running on 8081. Now i want to showcase the health status of server1 on UI(HTML) which is running on main app server(8081).I want to display the these elements on HTML.

1. Status code of server one.

2. Server is UP Or Down.

3. Response of the server one.

This is my nodejs code.

const express = require('express');
const http = require('http');
const fs = require('fs');
const bodyParser = require('body-parser');
const router = express.Router();
const path = require('path');
const ejs = require('ejs');
const app = express();
const server1 = express();



server1.get('/health', function (req, res, next) {
  res.json({health: true});
   res.status(200).end();
  });

app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.get('/', (req,res) => {
    res.render('index');
    console.log('server two')
  })

server1.listen(8080);
app.listen(8081);

Ajax part:

var xmlhttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4) {   
           if (xmlhttp.status == 200) {
               document.getElementById("#demo1").innerHTML = xmlhttp.responseText;
           }
           else if (xmlhttp.status == 400) {
              alert('There was an error 400');
           }
           else {
               document.getElementById('demo1').innerHTML = 'something else other than 200 was returned';
           }
        }
    };

    xmlhttp.open("GET", "http://localhost:8080/health", true);
    xmlhttp.send();

HTML:

<div id="demo1"></div>

What should i exactly do to display the health status of server1 on UI.

You could create a specific route that will be called on a specific setInterval() by your front-end javascript. This route could return a JSON with an errors array if there are any. Something along the lines of:

app.get('/health-check', (req,res) => {
    // check database connectivity and any other staff you want here 
    // add any errors in an array
    if (errors.length > 0) {
       return res.status(500).json({health: false, errors: errors});
    }
    return res.status(200).send({health: true});
  });

Be careful as there may exist errors that you don't want to show to your user. This will depend on the type of application etc.

Then make an AJAX call from your front-end JS code within a setInterval() function. The implementation of this will depend of the library/framework you use if you do but using jquery for example would be like:

const healthTimer = setInterval(() => {
  $.ajax({
    url: "[your server url]/health-check",
    type: "GET",
    success: function(xml, textStatus, xhr) {
        // get the server status here if everything is ok
        $('div.server-health span.success').text(`Server Status: ${xhr.status}`);
        $('div.server-health span.error').text('');
        console.log('RESPONSE CODE:', xhr.status);
    },
    error: function (request, status, error) {
        // handle the error rendering here
        $('div.server-health span.error').text(`Server Status: ${status}`);
        $('div.server-health span.success').text('');
        alert(request.responseText);
    }
});
}, 15000); // send the request every 15 seconds

Inside your html file you can have a <div> to show the server health:

<div class="server-health">
  <span class="error"></span>
  <span class="success"></span>
</div>

I've wrote and published a Node App with a React front-end that does exactly this. It's purely open source and free to use.

It allows you to define a list of websites, webapps, API endpoints and servers to monitor in JSON.

The React front-end provides a dashboard showing state of each asset. The backend will periodically call each 'asset' in your list and record state and response time and also broadcast the results to any connected client via Sockets.io.

Feel free to install as an NPM package, or go onto GitHub and clone the repo.

I understand you might not want an out of the box solution, so feel free to take a look at my code to help you in building your own solution.

NPM Link

GIT HUB Link

Running example on Heroku

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM