Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to automate POST request in NodeJS

I’m trying to automate my NodeJS app to automatically send POST requests every 2 minutes. Following is my code but I do not see the console logs or anything that proves me that it’s working. If I’m trying the POST request via POSTMAN it’s giving me the output correct. What might be wrong in my following code?

'user strict';
const express = require('express');
const config = require('./config');
const cors = require('cors');
const bodyParser = require('body-parser');
const eventRoutes = require('./routes/eventRoutes')

const app = express();

app.use(cors());
app.use(bodyParser.json());


app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    next();
  });
  
  app.get('/api', (req, res) => {
    request(
      { url: 'http://localhost:3507/api' },
      (error, response, body) => {
        if (error || response.statusCode !== 200) {
          return res.status(500).json({ type: 'error', message: err.message });
        }
  
        res.json(JSON.parse(body));
      }
    )
  });
  

var minutes = 2, the_interval = minutes * 60 * 1000;
setInterval(function() {
  app.post('/api/add', (req, res) => {
    console.log('Post Request!');
    request(
      { url: 'http://localhost:3507/api/add' },
      (error, response, body) => {
        if (error || response.statusCode !== 200) {
          return res.status(500).json({ type: 'error', message: err.message });
        }
  
        res.json(JSON.parse(body));
      }
    )
  });
}, the_interval);

app.use('/api', eventRoutes.routes)

app.listen(config.port, () => console.log(`Server is listening on http://localhost:` + config.port))

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

If this is the operation performing the HTTP request that you want to repeat on an interval:

request(
  { url: 'http://localhost:3507/api/add' },
  (error, response, body) => {
    if (error || response.statusCode !== 200) {
      return res.status(500).json({ type: 'error', message: err.message });
    }

    res.json(JSON.parse(body));
  }
)

Then that’s the operation you’d perform in an interval:

setInterval(() => {
  request(
    { url: 'http://localhost:3507/api/add' },
    (error, response, body) => {
      // do something with the response?
    }
  );
}, the_interval);

Note that the operation to handle the result has been removed because it doesn’t make sense outside the scope of an HTTP endpoint. (Which is what app.post(/*...*/) does, it creates an HTTP endpoint on your web server. You were trying to repeat that operation on an interval, which doesn’t really make sense.)

Note that it’s very unusual to do this. You’re essentially sending an HTTP request from your web server to some other web server every two minutes. The same request, over and over. Entirely in the background and unrelated to any requests that this web server receives.

So it’s entirely possible that this isn’t actually what you want to do, whatever you’re trying to accomplish. But if you do want to repeat this task from your web server every two minutes, you’d just wrap it in a setInterval.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading