我在Node JS中使用Express,并且想检查5分钟内是否没有POST请求,以便发送警报。
我们该如何解决?有人可以提出一些建议吗?
app.post('/apidata', function (request, response) {
var data = new dbData(request.body)
data.save()
.then(_item => {
response.send('Saved data to Database')
})
.catch(_err => {
response.status(400).send('Error while saving to Database. Contact Support.')
})
})
这是我的发帖请求。我需要检查是否正在调用此API。如果超过5分钟未致电,我需要发送警报。
答案 0 :(得分:1)
您可以编写一个middleware
用户,使其成为setTimeout
的用户,如下所示:-
function alertMiddleware(req, res, next) {
clearTimeout(req.app.locals.alertTimerID);
req.app.locals.alertTimerID = setTimeout(() => {
console.log('your message');
}, 60 * 1000 * 5);
next();
}
app.post('/apidata', alertMiddleware, (req,res,next) => {
//Your stuff here
});
答案 1 :(得分:0)
当然,您可以使用nodejs将发帖请求发送回您的服务器
step1: in your request method/function
// everytime you receive request, save that time in database or in a file
//get current time in milliseconds
var timeInMss = new Date().getTime()
var fs = require('fs');
fs.writeFile("/tmp/lastrequest.txt", timeInMss , function(err) {
if(err) {
return console.log(err);
}
console.log("The request time was saved!");
});
Step2:
//setup cron job running every 5 minutes
// install node-cron using command npm install --save node-cron
var cron = require('node-cron');
cron.schedule('* * * * *', () => {
console.log('running a task every minute');
//first get last request time read from file
var fs = require('fs');
fs.readFile("/tmp/lastrequest.txt", 'utf8', function(err, timedata) {
//check the time in timedata data if it is more than 5 minutes before current time, then send notification });
var http = require("http");
var options = {
host: 'youranotherserver',
port: 80,
path: '/serverpath',
method: 'POST'
};
var req = http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
});
req.write('data\n');
req.write('data\n');
req.end();