为什么在使用 ping 模块时在 NodeJS 中显示类型错误?

Why this is showing type error in NodeJS while using ping module?

我正在尝试制作一个基本应用程序来 ping 一个 IP。所以我的 HTML 表单接受一个输入 IP,然后 post 它到 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();
}); 

This is what comes on console

在我看来,这就是正在发生的事情:

  1. 您发出 ping 请求。请注意,它需要一个回调函数作为参数。这表明这是一个异步 I/O 操作。
  2. 你执行
res.write(msg);
res.send();

当时 msg 仍未定义,因此我猜测 res.write(msg) 实际上是 app.js 文件的第 30 行,错误是关于

  1. 才执行回调函数,但为时已晚

我建议按如下方式更改它

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