尝试HTTP请求时获得连接ECONNREFUSED 127.0.0.1:80

ng-*_*319 7 post get http request node.js

我正在尝试使用本地的node.js http模块向news.google.com发出http请求。我connect ECONNREFUSED 127.0.0.1:80尝试以下操作时出现错误

var http = require('http');

var payload = JSON.stringify({
    name: 'John Smith',
    email: 'john.smith@smith.com',
    resume: 'https://drive.google.com/open?id=asgsaegsehsehseh'
});

var options = {
    hostname: 'https://news.google.com',
    path: '/',
    method: 'GET'
};

var httpRequest = http.request(options, function(request, response) {
    console.log('STATUS', response.statusCode);
    response.setEncoding('utf8');

    response.on('data', function(chunk) {
        console.log('BODY:', chunk);
    });

    response.on('end', function() {
        console.log('No more data in response');
    });
});

httpRequest.on('error', function(e) {
    console.log('Error with the request:', e.message);
});

httpRequest.write(payload);
httpRequest.end();
Run Code Online (Sandbox Code Playgroud)

为什么会出现此错误?

我尝试使用requestnpm模块。而且有效!

ari*_*pen 41

我的问题是在使用supertestand 时jest。我的错误是没有将“/”作为某些 url 的前缀。因此,请仔细检查您提出的请求的 url 是否正确。

  • 有同样的经历。在使用“supertest”和“jest”执行请求之前忘记了前导“/”。Dziekuje bardzo。 (3认同)
  • 我有前导的“/”,但错误地还有一个不必要的“.”。谢谢你! (2认同)

Jas*_*ngh 18

就我而言,问题实际上是我使用的HTTP客户端的默认行为axios

默认情况下,127.0.0.1:80如果axios 找不到请求的URL或http方法(GET / POST / PUT),则会将我们重定向到。因此,最好也检查您的网址axios


Fro*_*ack 10

我正在使用 axios,get请求时发生此错误,通过在我的 URL 之前添加来解决它http://(在我的情况下,服务器是 http)


kei*_*hmo 5

这里有几个问题:

  1. 结构的hostname字段options应该只是主机,而不是 URL。在您的情况下,它应该只是'news.google.com'.

  2. request方法回调的签名是function (response)——你的function (request, response)。丢失第一个参数。

  3. 正如所写的那样,这将返回到 https 站点的 HTTP 重定向。替换var http = require('http');var https = require('https');,然后https在任何地方使用,而不是http