Node.js 错误:使用 http.request 时连接 ECONNREFUSED

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20488496/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:29:11  来源:igfitidea点击:

Node.js Error: connect ECONNREFUSED when using http.request

node.js

提问by jfcallo

I am troubleshooting a Node.js script, and have stripped out almost all of the code and still am able to reproduce the following error:

我正在对 Node.js 脚本进行故障排除,并且删除了几乎所有代码,但仍然能够重现以下错误:

{ 
  [Error: connect ECONNREFUSED]
  stack: 'Error: connect ECONNREFUSED 
          at exports._errnoException (util.js:682:11) 
          at Object.afterConnect [as oncomplete] (net.js:947:19)',
  code: 'ECONNREFUSED',
  errno: 'ECONNREFUSED',
  syscall: 'connect' 
}

The entire script is:

整个脚本是:

var http = require('http');

http.get("http://api.hostip.info/get_json.php", function(res) {
    console.log("Received response: " + res.statusCode);
});

var req = http.request(function(res) {
    console.log("Request began");
    var output = '';

    res.on('data', function (chunk) {
        output += chunk;
    });

    res.on('end', function () {
        console.log('Request complete:');
        console.log(output);
    });
});

req.on('error', function (err) {
    console.log(err);
    //console.log('error: ' + err.message);
});

req.end();
console.log("Script complete");

I'm confident this is a simple mistake somewhere in the code, but have been unable to identify the problem?

我确信这是代码中某个地方的一个简单错误,但一直无法确定问题所在?

回答by brandonscript

You haven't provided a url in http.request.

您尚未在 中提供网址http.request

Try var req = http.request("someurlhere", function(res) {... etc.

试试var req = http.request("someurlhere", function(res) {……等等。

Moreover, if you're using http.request like that, I can't quite see the purpose of the following block of code at all (maybe remnants from the rest of the completed script?)

此外,如果您像这样使用 http.request,我完全看不到以下代码块的用途(可能是已完成脚本的其余部分的残余部分?)

http.get("http://api.hostip.info/get_json.php", function(res) {
    console.log("Received response: " + res.statusCode);
});

回答by Aminadav Glickshtein

This question became popular, so I want to point you on a popular NodeJS library that make requesting much eaiser.

这个问题变得流行,所以我想向您指出一个流行的 NodeJS 库,它使请求变得更加容易。

This is my choice because it's using same syntax as fetchbrowsers api. So learing same syntax always better.

这是我的选择,因为它使用与fetch浏览器 api相同的语法。所以学习相同的语法总是更好。

It's also uses the new promises syntax, so you can use async/await

它还使用了新的 promises 语法,因此您可以使用 async/await

var fetch=require('node-fetch')
var data=await fetch(url);
var text=await data.text()

Learn more:

了解更多: