请求期间出现"套接字挂断"错误

Dmi*_*riy 22 node.js

我尝试通过node.js版本0.8.14的http模块向某个站点(不是我自己的站点)发出GET请求.这是我的代码(CoffeeScript):

options = 
        host: 'www.ya.ru'
        method: 'GET'
    req = http.request options, (res) ->
        output = ''
        console.log 'STATUS: ' + res.statusCode
        res.on 'data', (chunk) ->
            console.log 'A new chunk: ', chunk
            output += chunk

        res.on 'end', () ->
            console.log output
            console.log 'End GET Request'

    req.on 'error', (err) ->
        console.log 'Error: ', err
    req.end()
Run Code Online (Sandbox Code Playgroud)

我在此操作期间收到以下错误:{[错误:套接字挂断]代码:'ECONNRESET'}.如果我评论错误处理程序我的应用程序已完成以下错误:

events.js:48
    throw arguments[1]; // Unhandled 'error' event
    ^
Error: socket hang up
    at createHangUpError (http.js:1091:15)
    at Socket.onend (http.js:1154:27)
    at TCP.onread (net.js:363:26)
Run Code Online (Sandbox Code Playgroud)

我试图在互联网上找到解决方案,但仍然没有找到它们.如何解决这个问题?

use*_*109 32

你必须结束请求.在脚本的末尾添加:

req.end()
Run Code Online (Sandbox Code Playgroud)

  • 我添加了这一行(请查看更新的问题),但仍然会收到错误. (3认同)

Jon*_*ski 16

使用时http.request(),你必须在某个时候打电话request.end().

req = http.request options, (res) ->
    # ...

req.on 'error', # ...

req.end() # <---
Run Code Online (Sandbox Code Playgroud)

在那之前,它request是敞开的,允许写一个身体.并且,错误是因为服务器最终会认为连接已超时并将关闭它.

另外,您还可以使用http.get()GET要求,这将会调用.end(),因为自动GET请求通常不希望有一个机构.

  • @Dmitriy嗯.在顶部添加`http = require'http``,我能够看到当前片段的响应.您可以检查DNS以确保计算机可以到达服务器 - "require('dns').lookup('www.ya.ru',console.log);` (2认同)

Avi*_*Net 9

在我的情况下,它是'内容长度'标题 - 我把它拿出来,现在很好......

码:

function sendRequest(data)
{
    var options = {
              hostname: host,
              path: reqPath,
              port: port,
              method: method,
              headers: {
                      'Content-Length': '100'
              }
    var req = http.request(options, callback);
    req.end();
    };
Run Code Online (Sandbox Code Playgroud)

删除行后:'Content-Length':'100'整理出来.


Dmi*_*riy 5

我终于发现了问题并找到了解决方案.问题是我使用代理服务器连接到互联网.这是工作代码:

options = 
    hostname: 'myproxy.ru'
    path: 'http://www.ya.ru'
    port: 3128
    headers: {
        Host: "www.ya.ru"
    }
req = http.request options, (res) ->
    output = ''
    console.log 'STATUS: ' + res.statusCode
    res.on 'data', (chunk) ->
        console.log 'A new chunk: ', chunk
        output += chunk

    res.on 'end', () ->
        console.log output
        console.log 'End GET Request'

req.on 'error', (err) ->
    console.log 'Error: ', err
req.end()
Run Code Online (Sandbox Code Playgroud)

谢谢大家的帮助和建议!