简体   繁体   English

如何在HTML上显示节点服务器的运行状况

[英]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. 一个是运行在端口8080上的server1,另一个是运行在8081上的主应用程序服务器。现在,我想在运行在主应用程序服务器(8081)上的UI(HTML)上显示server1的运行状况。 HTML上的这些元素。

1. Status code of server one. 1. Status code of server one.

2. Server is UP Or Down. 2. Server is UP Or Down.

3. Response of the server one. 3. Response of the server one.

This is my nodejs code. 这是我的nodejs代码。

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: Ajax部分:

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: HTML:

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

What should i exactly do to display the health status of server1 on UI. 我应该怎么做才能在UI上显示server1的运行状况。

You could create a specific route that will be called on a specific setInterval() by your front-end javascript. 您可以创建一个特定的路由,该路由将由您的前端javascript在特定的setInterval()上调用。 This route could return a JSON with an errors array if there are any. 如果存在,此路由可能返回带有错误数组的JSON。 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. 然后在setInterval()函数中从您的前端JS代码进行AJAX调用。 The implementation of this will depend of the library/framework you use if you do but using jquery for example would be like: 如果要这样做,将取决于您使用的库/框架,但是例如,使用jquery将像这样:

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: 在html文件中,您可以使用<div>来显示服务器的运行状况:

<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. 我已经编写并发布了一个具有React前端的Node App,它可以做到这一点。 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. 它允许您定义要在JSON中监视的网站,Web应用程序,API端点和服务器的列表。

The React front-end provides a dashboard showing state of each asset. React前端提供了一个显示每个资产状态的仪表板。 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. 后端将定期调用列表中的每个“资产”,并记录状态和响应时间,并通过Sockets.io将结果广播到任何连接的客户端。

Feel free to install as an NPM package, or go onto GitHub and clone the repo. 可以以NPM软件包的形式随意安装,也可以转到GitHub并克隆存储库。

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 NPM连结

GIT HUB Link GIT HUB链接

Running example on Heroku 在Heroku上运行示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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