【问题标题】:Why this is showing type error in NodeJS while using ping module?为什么在使用 ping 模块时在 NodeJS 中显示类型错误?
【发布时间】:2022-02-03 17:18:37
【问题描述】:

我正在尝试制作一个基本的应用程序来 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();
}); 

This is what comes on console

【问题讨论】:

  • 该错误抱怨 app.js 中的第 30 行。这段代码 sn-p 的哪一行是第 30 行?

标签: javascript node.js express npm ping


【解决方案1】:

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

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

【讨论】:

  • 非常感谢@Kamil Janowski。这正是我的代码中发生的事情,在您提出建议后我能够纠正。现在一切正常。
  • 我很高兴能帮上忙。在这一点上,如果您可以对我的答案进行投票和/或将其标记为正确答案,那就太好了:P 只有这样您的问题才会被标记为“已回答”,我将获得我的声誉积分:P
  • 抱歉,我是这个平台的新手。
猜你喜欢
  • 2021-12-15
  • 2022-01-23
  • 2018-06-03
  • 1970-01-01
  • 2022-06-15
  • 2021-08-08
  • 1970-01-01
  • 1970-01-01
  • 2022-06-10
相关资源
最近更新 更多