我正在尝试制作一个基本的应用程序来ping IP。因此,我的HTML表单采用一个输入IP并将其发布到NodeJS。我正在使用ping模块来获取结果。如果我静态地输入一个IP,它可以很好地工作,但当我试图通过HTML形式获取IP时,它就会中断。这就是我的代码的样子。
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();
});
这是控制台上的内容
在我看来,这就是正在发生的事情:
- 您发出ping请求。请注意,它将回调函数作为参数。这表明这是一个异步I/O操作
- 你执行
res.write(msg);
res.send();
当时msg
还没有定义,因此我猜测res.write(msg)
实际上是app.js文件的第30行,错误都是关于的
- 只有执行回调函数,但为时已晚
我建议按以下进行更改
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();
});
});