简体   繁体   中英

setInterval in nodejs

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM