4

I am making an http request which should run after every one minute. Below is my code

var express = require("express");
var app = express();
var recursive = function () {
    app.get('/', function (req, res) {
        console.log(req);
        //Some other function call in callabck
        res.send('hello world');
    });
    app.listen(8000);
    setTimeout(recursive, 100000);
}
recursive();

According to the above code, I must get response after every one minute. But I am getting Error: listen EADDRINUSE. Any help on this will be really helpful.

gp.
  • 7,443
  • 3
  • 34
  • 37
user134414214
  • 73
  • 1
  • 1
  • 7
  • 1
    possible duplicate of [nodejs Error: listen EADDRINUSE](http://stackoverflow.com/questions/9898372/nodejs-error-listen-eaddrinuse) – Colin Brock Nov 13 '14 at 05:43
  • but here im using setInterval. Any idea on this? – user134414214 Nov 13 '14 at 05:44
  • your code starts a server at 8000 port and sets a handler for handling get request to '/'. You need to do this only once. Another point, you are not actually making a call to your server so no response every minute. – gp. Nov 13 '14 at 05:44
  • Thanks for quick reply. So how can I make it work? – user134414214 Nov 13 '14 at 05:49
  • 2
    your task is completely incorrect. Think more about actual issue you try to solve. – vp_arth Nov 13 '14 at 05:58
  • `app.get` is a directive only for handle incoming requests, not a request. – vp_arth Nov 13 '14 at 05:59
  • I think you are trying to create node httpclient (http.request) which sends request to server, but instead you have created httpserver.. – Amitesh Nov 13 '14 at 06:13

2 Answers2

7

This code makes http requests every minute:

var http = require('http');

var options = {
  host: 'example.com',
  port: 80,
  path: '/'
};
function request() {
  http.get(options, function(res){
    res.on('data', function(chunk){
       console.log(chunk);
    });
  }).on("error", function(e){
    console.log("Got error: " + e.message);
  });
}
setInterval(request, 60000);
vp_arth
  • 12,796
  • 4
  • 33
  • 59
4

EADDRINUSE error is thrown because you can't start a server in the same port twice

It would work of the next way:

var express = require("express"),
    app = express(),
    recursive = function (req, res) {
        console.log(req);
        //Some other function call in callabck
        res.send('hello world');
        setTimeout(recursive, 100000);
    };
    app.get('/', recursive);
    app.listen(8000); 
}
ariel_556
  • 358
  • 1
  • 9