Bharat Bittu
Bharat Bittu

Reputation: 525

Can we check if we are getting POST request call from another server?

I am using Express in Node JS and want to check if there is no POST request for 5 minutes so that I can send Alert.

How do we solve this? Can someone please suggest some ideas.

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.')
  })
})

This is my post request. I need to check if this API is being called. If it is not called for more than 5 minutes, I need to send alert.

Upvotes: 1

Views: 1570

Answers (2)

vibhor1997a
vibhor1997a

Reputation: 2376

You can write a middleware that makes user of setTimeout like below:-

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
});

Upvotes: 1

magegaga.com
magegaga.com

Reputation: 500

offcourse, you can send post request back to your server using 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();

Upvotes: 0

Related Questions