I'm trying to make a basic app to ping an IP. So my HTML form takes one input IP and post it to NodeJS. I'm using ping module to get the results. it works fine if I enter an IP statically but when I try to get IP by HTML form it just breaks. This is how my code looks.
app.post("/",function(req,res){
console.log(req.body);
var ip= req.body.ip;
console.log(typeof(ip));
var msg;
var hosts = [ip];
hosts.forEach(function(host){
ping.sys.probe(host, function(isAlive){
console.log(isAlive);
msg = isAlive ? 'host ' + host + ' is alive' : 'host ' + host + ' is dead';
console.log(msg);
});
});
res.write(msg);
res.send();
});
The way I see it, this is what is happening:
res.write(msg);
res.send();
At the time msg is still undefined and therefore I'm guessing that res.write(msg) is in fact the line 30 of app.js file that the error is all about
I would recommend changing it as follows
app.post("/",function(req,res){
console.log(req.body);
const ip= req.body.ip;
console.log(typeof(ip));
ping.sys.probe(ip, function(isAlive){
console.log(isAlive);
const msg = isAlive ? 'host ' + host + ' is alive' : 'host ' + host + ' is dead';
console.log(msg);
res.write(msg);
res.send();
});
});