Socket hang up ошибка vexera

Postman Community

Loading

There are two cases when socket hang up gets thrown:

When you are a client

When you, as a client, send a request to a remote server, and receive no timely response. Your socket is ended which throws this error. You should catch this error and decide how to handle it: whether retry the request, queue it for later, etc.

When you are a server/proxy

When you, as a server, perhaps a proxy server, receive a request from a client, then start acting upon it (or relay the request to the upstream server), and before you have prepared the response, the client decides to cancel/abort the request.

This stack trace shows what happens when a client cancels the request.

Trace: { [Error: socket hang up] code: 'ECONNRESET' }
    at ClientRequest.proxyError (your_server_code_error_handler.js:137:15)
    at ClientRequest.emit (events.js:117:20)
    at Socket.socketCloseListener (http.js:1526:9)
    at Socket.emit (events.js:95:17)
    at TCP.close (net.js:465:12)

Line http.js:1526:9points to the same socketCloseListener mentioned by @Blender, particularly:

// This socket error fired before we started to
// receive a response. The error needs to
// fire on the request.
req.emit('error', createHangUpError());

...

function createHangUpError() {
  var error = new Error('socket hang up');
  error.code = 'ECONNRESET';
  return error;
}

This is a typical case if the client is a user in the browser. The request to load some resource/page takes long, and users simply refresh the page. Such action causes the previous request to get aborted which on your server side throws this error.

Since this error is caused by the wish of a client, they don’t expect to receive any error message. So, no need to consider this error as critical. Just ignore it. This is encouraged by the fact that on such error the res socket that your client listened to is, though still writable, destroyed.

console.log(res.socket.destroyed); //true

So, no point to send anything, except explicitly closing the response object:

res.end();

However, what you should do for sure if you are a proxy server which has already relayed the request to the upstream, is to abort your internal request to the upstream, indicating your lack of interest in the response, which in turn will tell the upstream server to, perhaps, stop an expensive operation.

Я пытаюсь сделать запрос GET на какой-то сайт (не мой собственный сайт) через http-модуль узла.Яш версию 0.8.14. Вот мой код (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()

во время этой операции я получаю следующую ошибку: { [Ошибка: socket hang up] код: ‘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)

Я пытаюсь найти решение в интернете, но до сих пор не нашли их. Как решить эту проблему?

7 ответов


вы должны завершить запрос. Добавьте это в конце вашего скрипта:

req.end()

при использовании http.request(), вы должны в какой-то момент вызов request.end().

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

req.on 'error', # ...

req.end() # <---

до request остается открытым, чтобы разрешить написании тело. И ошибка заключается в том, что сервер в конечном итоге сочтет соединение истекшим и закроет его.

кроме того, вы также можете использовать http.get() С GET запросы, которые будем называть .end() автоматически начиная с GET запросы обычно не ожидается, что тело.

15

автор: Jonathan Lonowski


в моем случае это был ‘Content-Length’ заголовок-я вытащил его, и теперь все в порядке…

код:

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

после удаления строки: ‘Content-Length’:’100′ он разобрался.


Я, наконец, обнаружил проблему и нашли решение. Проблема в том, что я использую прокси-сервер для подключения к интернету. Вот рабочий код:

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

спасибо всем за помощь и предложения!


Я обнаружил, что это происходит в одном случае, когда я отправлял пустое тело, как — ‘{}’ в операции delete вызывается из интерн фреймворк для тестирования;
вместо этого я использовал null для отправки в качестве значения параметра body при выполнении запроса через


при обновлении с 0.10.33 до 0.12 nodejs эта ошибка была нажата.

в моем случае для запроса на удаление было тело (json). Ранее клиент узла устанавливал-‘ transfer — encoding ‘как chunked-по умолчанию, когда» content-length » не установлен. Кажется, в последней версии клиент узла перестал устанавливать передачу-кодирование по умолчанию.

Fix должен был установить его в запросе.


в моем случае, после обновления до node 8.0.0 пост не работает. добавление Content-Length заголовок не помогает. Нужно добавить 'Connection': 'keep-alive' до заголовок чтобы получить эту ошибку подальше.

    let postOptions = {
        method: 'POST',
        form: form,
        url: finalUrl,
        followRedirect: false,
        headers:{
            'Connection': 'keep-alive'
        }
    };
    request(postOptions, handleSAMLResponse);

Socket hang up is an error that occurs in network applications when the server does not respond to your connection requests due to your configuration error or excessive load on the server.Socket Hang Up

The error can happen in your connection code and that’s what we’ll talk about and show you solutions that will work for you. The information contained in this article will show you what happens behind the scenes of a network connection and what can make it fail.

Now, let’s teach you how to fix socket hang up error message after we explain the possible reasons behind the error.

Contents

  • Why Is the Server Hanging Up Your Connection? Major Culprits
    • – Your URL Path Is Wrong
    • – You Did Not Finish Your Request
    • – You’re Connecting to an HTTPS Service Using HTTP
    • – An Application Is Blocking Your Connection
    • – You Sent Excessive Requests to a Server
    • – Two Applications Are Using the Same Port
  • How Can the Server Accept Your Connection? Most Seamless Solutions
    • – Update Your URL Path
    • – End Your Request Using “request.end()”
    • – Connect to an HTTPS Service Using HTTPS
    • – Switch off the Proxy or Your Vpn
    • – Reduce Your Requests to the Server
    • – Use Different Ports for Your Applications
  • Conclusion

Why Is the Server Hanging Up Your Connection? Major Culprits

The server is hanging up your connection because of the following:

  • Your URL path is wrong
  • You did not finish your request
  • You’re connecting to an HTTPS service using HTTP
  • An application is blocking your connection
  • You sent excessive requests to a server
  • Two applications are using the same port

– Your URL Path Is Wrong

This happens in “Node.js” when you’re connecting using “Express.js” to make the request, and your path for the request is wrong. This means the server was expecting a particular path in your request, but it- got something else that led to the termination of your connection.

For example, the following is an “Express.js” server code that expects that your URL to the server should have “/user/login”. However, if you hit the server with “user/login”, you’ll get the “socket hang up error.

const express = require(‘express’);

const app = express();

app.get(‘/user/login’, (req, res) => {

res.send(‘Successful login’);

});

app.listen(3000, () => {

console.log(‘Server started on http://localhost:3000’);

});

– You Did Not Finish Your Request

When you make a request to a server and you abruptly end the request before the server can fulfill it, you’ll get the “socket hang up” error. For example, using an HTTP method, the following “Node.js” code will request a Wikipedia page.Socket Hang Up Causes

After the request, we did not finish it, and it’s a sign that we’re asking the server for the information. So, when you run the code, you’ll get an error.

var https = require(“https”);

var options = {

host: “en.wikipedia.org”,

path: “<path_to_wiki_page>”,

port: <secure_port_number>,

method: “<HTTP_METHOD>”

};

var request = https.request(options, function (response) {

console.log(response.statusCode);

});

– You’re Connecting to an HTTPS Service Using HTTP

When a service only accepts an HTTPS connection, it will reject an HTTP connection with the “socket hang up” message.

For example, the following “Node.js” code is trying to consume HTTPS using the “http” module. This will lead to an error because the service is configured to accept HTTPS connection.

As a result it will close your HTTP connection:

const http = require(‘http’);

const options = {

hostname: ‘site.example’,

port: 443,

path: ‘/’,

method: ‘GET’

};

const req = http.request(options, (res) => {

console.log(`statusCode: ${res.statusCode}`);

res.on(‘data’, (d) => {

process.stdout.write(d);

});

});

req.on(‘error’, (error) => {

console.error(error);

});

req.end();

– An Application Is Blocking Your Connection

A VPN application or a proxy server can disrupt your connection to the server, leading to multiple “socket hang up” errors. For a VPN, it can block your connection if the remote server is not part of its “allow list.

For the proxy server, it happens in the Axios library when the “Node.js” proxy tampers with the connection. In either case, your connection will not complete, and this causes your client application to show an error.

– You Sent Excessive Requests to a Server

If you send excessive requests to a server, at one point, it’ll start rejecting your request with the “socket hang up” error. These requests can be the result of your web scraping that’s causing the server to use up more of its resources.

At a point, it’ll become overwhelmed, like what happens in a Distributed Denial of Service Attack (DDoS), and it will not accept your request.

– Two Applications Are Using the Same Port

When two network applications, NA_1 and NA_2, are using the same port on your computer, one of them will produce the “socket hang up” error. The reason behind this is that each port on your computer can only be bound to one application at a time.

So, if NA_1 binds to a port, it tells your operating system that it wants to use the port to receive incoming network traffic. However, when NA_2 tries to bind to the same port, your operating system will not allow it because the port is already in use by NA_1.

How Can the Server Accept Your Connection? Most Seamless Solutions

The server can accept your connection if you do any of the following:

  • Update your URL path
  • End your request using “request.end()”
  • Connect to an HTTPS service using HTTPS
  • Switch off the proxy or your VPN
  • Reduce your requests to the server
  • Use different ports for your applications



– Update Your URL Path

Updating your URL path will fix the “socket hang up nodejs” error. The following is a previous “Node.js” code that we showed you earlier:

const express = require(‘express’);

const app = express();

app.get(‘/user/login’, (req, res) => {

res.send(‘Successful login’);

});

app.listen(3000, () => {

console.log(‘Server started on http://localhost:3000’);

The best way to hit the server is via a URL like “http://localhost:3000/user/login”. Any other form will lead to an error. So, if you’re getting this error in your “Node.js” application, ensure that you’re using the right URL path.

– End Your Request Using “request.end()”

When you send a request to a server, always end your request using “request.end()”. For example, the following is an updated version of a previous code that caused the “socket hang up error.

This time, we’re ending the connection using “request.end()” and you can use the same approach to fix “socket hang up golang“.

var https = require(“https”);

var options = {

host: “en.wikipedia.org”,

path: “<path_to_wiki_page>”,

port: <secure_port_number>,

method: “<HTTP_METHOD>”

};

var request = https.request(options, function (response) {

console.log(response.statusCode);

});

request.end() // Here is the fix.

– Connect to an HTTPS Service Using HTTPS

Making a connection to an HTTPS service using an HTTPS connection will prevent the “socket hang up Postman error.Socket Hang Up Fixes

In “Node.js”, you must communicate with HTTPS using the “https” module. That’s the update in the following code that will prevent the socket error:

/* Before:

const http = require(‘http’);

*/

// Update:

const https = require(‘https’);

const options = {

# hostname: ‘site.example’,

port: 443,

path: ‘/’,

method: ‘GET’

};

const req = https.request(options, (res) => {

console.log(`statusCode: ${res.statusCode}`);

res.on(‘data’, (d) => {

process.stdout.write(d);

});

});

req.on(‘error’, (error) => {

console.error(error);

});

req.end();

– Switch off the Proxy or Your Vpn

Switching off the proxy settings in “Node.js” will prevent the “socket hang up axios” error. You can do this by adding the following to your “axios.js” file:

delete process.env[‘http_proxy’];

delete process.env[‘HTTP_PROXY’];

delete process.env[‘https_proxy’];

delete process.env[‘HTTPS_PROXY’];

– Reduce Your Requests to the Server

When a server like NGINX starts rejecting your connection requests, reduce the number of requests, and you’ll solve the “nginx socket hang up” error.

For example, if you’re scraping a website using 2000 simultaneous connections, drop it to a certain amount the server will accept. Afterward, do not exceed this number, and the server will not respond with the “socket hang up” error.

– Use Different Ports for Your Applications

If your investigation reveals that two applications on your computer are using the same port, update their configuration to use different ports. This will prevent the “socket hang up ECONNRESET” error in your network applications.

For example, in “Next.js” and “Nest.js”, you can update their environment files (env files) to use the same port. Use the same procedure for other applications that have a configuration file that can set the hostname and port numbers.

Conclusion

This article explained the causes of the “socket hang up” error and solutions that you can use depending on your use case. We’ll leave you with the following “must-know” from our discussion:

  • Excessive connection requests to a server can cause the server to throw the “socket hang up” error.
  • An HTTP connection to an HTTPS service will also lead to the “socket hang up” error because the server will reject the connection.
  • To solve the “socket hang up” error, ensure that two applications are not using the same port and you end your request in your “Node.js” applications.
  • Always consume an HTTPS service using HTTPS.

To retain what you’ve learned, find a friend and teach them how “socket hang up” can occur in a network connection. We hope you enjoyed reading it as we enjoyed writing the correct code.

  • Author
  • Recent Posts

Position is Everything

Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team

Position is Everything

Hi, i know that such issues were created before, but there was a little bit different description.

I tried to perform simple request: send form data. But when i use request module it always throw «socket hang up».

Below simple test case and results

'use strict';

const request = require('request');
const http = require('http');
const querystring = require('querystring');

const data = {
    xstext: 'I have a some problem about node.js server. What should I do to solve the this problem?',
    spintype: 0,
    removeold: 0,
};

// Using request
request(
    {
        method: 'POST',
        url: 'http://address:9017/',
        form: data,
    },
    (error, responce, body) => {
        if (!error) {
            console.log(body, responce);
            return;
        }
        console.log(error);
    }
);

// Using native http
let postData = querystring.stringify(data);

let options = {
    hostname: 'address',
    port: 9017,
    path: '/',
    method: 'POST',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Content-Length': postData.length,
    },
};

let req = http.request(options, (res) => {
    console.log(`STATUS: ${res.statusCode}`);
    console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
    res.setEncoding('utf8');
    res.on('data', (chunk) => {
        console.log(`BODY: ${chunk}`);
    });
    res.on('end', () => {
        console.log('No more data in response.');
    });
});

req.on('error', (e) => {
    console.log(`problem with request: ${e.message}`);
});

req.write(postData);
req.end();

For request module:

{ [Error: socket hang up] code: 'ECONNRESET' }

For native http:

STATUS: 200
HEADERS: {"content-length":"98","content-type":"text/html","cache-control":"no-cache","connection":"keep-close"}
BODY: Excellent some problem about client. js server. What must i do to solve the particular this issue?
No more data in response.

Loks like it’s really bug in request module.

Понравилась статья? Поделить с друзьями:
  • Socket bind failed on local address openvpn ошибка
  • Sokkia cx ошибка e031
  • Sony vegas pro ошибка при запуске
  • Solvercode excel 2013 ошибка что делать
  • Socialkit ошибка 500