NodeJS请求 - 总是返回econnrefused

nodejs request - always returning econnrefused

本文关键字:返回 econnrefused 请求 NodeJS      更新时间:2023-09-26

我使用昨天工作的模块cheerio,request和longjohn编写了一些代码,但今天它总是抛出"ECONNREFUSED"错误。

我尝试使用使用请求的简单示例代码:

var request = require('request');
request('http://www.google.com', function (error, response, body) {
    if (!error && response.statusCode == 200) {
        console.log(body) // Show the HTML for the Google homepage.
    }
    else{
        console.log(error);
    }
})

但它仍然返回:

{[Error: connect ECONNREFUSED]
    code: 'ECONNREFUSED',
    errno: 'ECONNREFUSED',
    syscall: 'connect' }

只是想知道这可能是什么原因,我可以使用网络浏览器很好地连接到互联网。

谢谢

这可能是因为由于防火墙或代理,该进程无法访问互联网。

检查您的防火墙和代理设置,并确保进程可以访问互联网。

我的问题是我在启动服务器进程后立即执行获取。我通过将 get 包装在设置超时中解决了错误

setTimeout(() => {
  http.get('http://localhost:4003/state', (response) => {
    console.log('response:', response)
    response = response;
    server.kill('SIGTERM');
  }).on('error', (err) => {
    console.log('error:', err)
    server.kill('SIGTERM');
  });
}, 1000);