[英]How to show health status of node server on HTML
我有兩台服務器。 一個是運行在端口8080上的server1,另一個是運行在8081上的主應用程序服務器。現在,我想在運行在主應用程序服務器(8081)上的UI(HTML)上顯示server1的運行狀況。 HTML上的這些元素。
1. Status code of server one.
2. Server is UP Or Down.
3. Response of the server one.
這是我的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部分:
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>
我應該怎么做才能在UI上顯示server1的運行狀況。
您可以創建一個特定的路由,該路由將由您的前端javascript在特定的setInterval()
上調用。 如果存在,此路由可能返回帶有錯誤數組的JSON。 類似於以下內容:
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});
});
請小心,因為可能存在您不想顯示給用戶的錯誤。 這將取決於應用程序的類型等。
然后在setInterval()
函數中從您的前端JS代碼進行AJAX調用。 如果要這樣做,將取決於您使用的庫/框架,但是例如,使用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
在html文件中,您可以使用<div>
來顯示服務器的運行狀況:
<div class="server-health">
<span class="error"></span>
<span class="success"></span>
</div>
我已經編寫並發布了一個具有React前端的Node App,它可以做到這一點。 它是純開源的,可以免費使用。
它允許您定義要在JSON中監視的網站,Web應用程序,API端點和服務器的列表。
React前端提供了一個顯示每個資產狀態的儀表板。 后端將定期調用列表中的每個“資產”,並記錄狀態和響應時間,並通過Sockets.io將結果廣播到任何連接的客戶端。
可以以NPM軟件包的形式隨意安裝,也可以轉到GitHub並克隆存儲庫。
我了解您可能不希望使用現成的解決方案,所以請隨時查看我的代碼以幫助您構建自己的解決方案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.