Error read econnreset postman что за ошибка

Postman is stuck at a «GET» request, giving error that «Could not get response Error: read ECONNRESET» in Node JS using PostgreSQL as backend

I am following a video tutorial on login authentication using JWT Tokens.

I made up a database on PostgreSQL, connected it with my Node JS server and tested out registration and login commands. Both the queries worked fine on Postman and Postman returned the expected results.

Now, on logging in, I get a JWT Token in returning value, which is to be used further to get the user ID who’s logged in and his information.

So, to test if that token is working or not, I made a route which verifies if the user is logged in or not. (It is added in the same file in which login and registration routes are)

Code of this route file file is as follows (jwAuth.js). I have not added codes of Registration and Login in it

The code for the middleware authorization.js is as follows,

I also tried the same thing on another route, dashboard.js which was supposed to return/print the ID of the user using the JWT Token given to it, conditioned that the user is logged in correctly

The code of dashboard.js is as follows,

And the code for my index.js (or server.js) is as follows,

My problem is, If I try to send request to the following links with the required data, Postman works fine and data is also added in my database (and is also retrieved correctly while checking for login)

But when I try the same thing with this URL (by giving the JWT Token in the Header of the Postman GET Request,

Postman gets stuck, takes a long time in processing the request and ultimately gives this error,

Could not get response Error: read ECONNRESET

I tried searching this error up and apparently the fix of this issue is adding an IP address of localhost in etc/hosts file but in that case, my registration and login POST Requests would not have worked either. I am unable to figure out the problem so kindly someone please help.

Just to be sure, I have shared below the etc/hosts file as well and the Registration/Login Routes along with jwtGenerator file

Источник

How do I debug error ECONNRESET in Node.js?

I’m running an Express.js application using Socket.io for a chat webapp and I get the following error randomly around 5 times during 24h. The node process is wrapped in forever and it restarts itself immediately.

The problem is that restarting Express kicks my users out of their rooms and nobody wants that.

The web server is proxied by HAProxy. There are no socket stability issues, just using websockets and flashsockets transports. I cannot reproduce this on purpose.

This is the error with Node v0.10.11 :

EDIT (2013-07-22)

Added both socket.io client error handler and the uncaught exception handler. Seems that this one catches the error:

So I suspect it’s not a Socket.io issue but an HTTP request to another server that I do or a MySQL/Redis connection. The problem is that the error stack doesn’t help me identify my code issue. Here is the log output:

How do I know what causes this? How do I get more out of the error?

Ok, not very verbose but here’s the stacktrace with Longjohn:

Here I serve the flash socket policy file:

Can this be the cause?

16 Answers 16

You might have guessed it already: it’s a connection error.

«ECONNRESET» means the other side of the TCP conversation abruptly closed its end of the connection. This is most probably due to one or more application protocol errors. You could look at the API server logs to see if it complains about something.

But since you are also looking for a way to check the error and potentially debug the problem, you should take a look at «How to debug a socket hang up error in NodeJS?» which was posted at stackoverflow in relation to an alike question.

Quick and dirty solution for development:

Use longjohn, you get long stack traces that will contain the async operations.

Clean and correct solution: Technically, in node, whenever you emit an ‘error’ event and no one listens to it, it will throw. To make it not throw, put a listener on it and handle it yourself. That way you can log the error with more information.

To have one listener for a group of calls you can use domains and also catch other errors on runtime. Make sure each async operation related to http(Server/Client) is in different domain context comparing to the other parts of the code, the domain will automatically listen to the error events and will propagate it to it’s own handler. So you only listen to that handler and get the error data. You also get more information for free.

EDIT (2013-07-22)

«ECONNRESET» means the other side of the TCP conversation abruptly closed its end of the connection. This is most probably due to one or more application protocol errors. You could look at the API server logs to see if it complains about something.

What could also be the case: at random times, the other side is overloaded and simply kills the connection as a result. If that’s the case, depends on what you’re connecting to exactly…

But one thing’s for sure: you indeed have a read error on your TCP connection which causes the exception. You can see that by looking at the error code you posted in your edit, which confirms it.

Источник

Как мне отладить ошибку ECONNRESET в Node.js?

Я запускаю приложение Express.js, используя Socket.io для веб-приложения чата, и случайно получаю следующую ошибку примерно 5 раз в течение 24 часов. Процесс узла заворачивается навсегда и сразу же перезапускается.

Проблема в том, что перезапуск Express выбивает моих пользователей из их комнат, и никто не хочет этого.

Веб-сервер прокси HAProxy. Нет проблем со стабильностью сокетов, только при использовании веб-сокетов и транспортов flashsockets. Я не могу воспроизвести это специально.

Это ошибка с узлом v0.10.11 :

РЕДАКТИРОВАТЬ (2013-07-22)

Добавлен как клиентский обработчик ошибок socket.io, так и обработчик необработанных исключений. Кажется, что этот ловит ошибку:

Поэтому я подозреваю, что это не проблема Socket.io, а HTTP-запрос к другому серверу, который я делаю, или соединение MySQL / Redis. Проблема в том, что стек ошибок не помогает мне определить мою проблему с кодом. Вот вывод журнала:

Как я знаю, что вызывает это? Как я могу получить больше от ошибки?

Хорошо, не очень многословно, но вот трассировка стека с Longjohn:

Здесь я использую файл политики флэш-сокета:

Может ли это быть причиной?

Возможно, вы уже догадались: это ошибка соединения.

«ECONNRESET» означает, что другая сторона диалога TCP внезапно закрыла свой конец соединения. Скорее всего, это связано с одной или несколькими ошибками протокола приложения. Вы можете просмотреть журналы сервера API, чтобы увидеть, если он жалуется на что-то.

Но так как вы также ищете способ проверить ошибку и, возможно, устранить ее, вы должны взглянуть на « Как отладить ошибку зависания сокета в NodeJS? », Которая была опубликована в stackoverflow по аналогичному вопросу.

Быстрое и грязное решение для разработки :

Чтобы иметь одного слушателя для группы вызовов, вы можете использовать домены, а также ловить другие ошибки во время выполнения. Убедитесь, что каждая асинхронная операция, относящаяся к http (сервер / клиент), находится в различном контексте домена, по сравнению с другими частями кода, домен автоматически прослушивает error события и передает его своему собственному обработчику. Таким образом, вы только слушаете этот обработчик и получаете данные об ошибках. Вы также получите больше информации бесплатно.

РЕДАКТИРОВАТЬ (2013-07-22)

Как я уже писал выше:

«ECONNRESET» означает, что другая сторона диалога TCP внезапно закрыла свой конец соединения. Скорее всего, это связано с одной или несколькими ошибками протокола приложения. Вы можете просмотреть журналы сервера API, чтобы увидеть, если он жалуется на что-то.

Но одна вещь наверняка: у вас действительно есть ошибка чтения на вашем соединении TCP, которое вызывает исключение. Это можно увидеть, посмотрев код ошибки, который вы опубликовали в своем редактировании, что подтверждает это.

Источник

Error: read ECONNRESET #314

Comments

klammbueddel commented Mar 27, 2013

Hi brianc,
this is my first Bug report, so please don’t blame me for bad style:)

I have an issue with loosing connections. This happens after upgrading to node v0.10.1. I used v.8x? before and it worked. I am developing with Windows 8.

Maybe this happens because the Garbage Collector was modified in the new release?
I wrote a simple mocha test that shows the problem.
var pg = require(‘pg’);

Debugging this lead me to the assumption, that it is caused by the garbage collector, that is trying to destroy the tcp socket used by the database, but maybe I am completly wrong with this.

The text was updated successfully, but these errors were encountered:

brianc commented Mar 28, 2013

I think you might have hit on a valid issue. Just so I know we’re both speaking the same language: what’s happening is you’re checking out a client from the pool and issuing one query on the client. When the query returns you are returning the client back to the pool. As a default behavior, after 30 seconds the pool will close any client which has been sitting idle for 30 seconds. When the pool does its background close of your client, the client is emitting an error (not closing cleanly). That’s definitely crappy, hard to test, «gotcha» behavior I’d like to address asap.

Also, @klammbueddel I would never think about blaming you for bad style. You’ve picked a good repo to submit a bug to. I might not be the fastest at fixing them, but I always try to be polite. 😄 Not to mention your bug report was solid. The only thing missing is what version of node-postgres & PostgreSQL you’re running, but in this case it’s not even a big deal. I’ll get to work trying to reproduce this as soon as possible.

brianc commented Mar 28, 2013

Hey @klammbueddel, ofcourse I cannot reproduce here.

Try running this script:

and copy/paste your console output back to me.

What you should see is the time result record being logged, the nothing for 30 seconds. After that the pool idle sweep will kick in and (hopefully) gracefully shutdown your client.

note: you might need to specify connection parameters unless you are using environment variables

klammbueddel commented Mar 28, 2013

Hi @brianc, thanks for your fast reply!!
Yes, obviously it is not a problem with the gc of v8 but with the termination of the db connections. In the taskmanager the list of postgres instances increases like evil when i keep my app running for a while.
I attached the log. As you can see the postgres error repeats in a 30sec interval. The stream error occures only once. The stream end event never fires as it should.

I use postgresql-9.2.1-1-windows-x64 and postgres-node 0.14.1
I have the same issue with 0.12.x on node-v0.10.1-x86 as well as node-v0.10.1-x64. Downgrading to node-v0.8.18-x64 fixes the issue.

brianc commented Mar 28, 2013

That sucks I can’t reproduce that. I have a good feeling I know where the issue is. is there a way you could get the actual stacktrace out of the error?

err.stack should have it. Also, if you just run the query once and leave the pool idle forever and ever you get the error every 30 seconds? That’s extra weird.

Also, if you want to make your test faster you can do require(‘pg’).defaults.poolIdleTimeout = 5000 or something

klammbueddel commented Mar 28, 2013

The interval shortens until the error fires every second and creates a new pg process each time. I added the timing (poolIdleTimeout = 5000), hope that helps.

it continues each second from then on.

brianc commented Mar 28, 2013

Sorry. still cannot reproduce. could you do one more thing for me?

in the script I sent you, modify it like so:

This will log out all the incoming protocol messages. It will also throw and kill the process after the first error. That way I don’t get more output than I need. Then just copy/paste the entire terminal output.

klammbueddel commented Mar 28, 2013

thanks for the support. I am afk for some hours, will post the trace later.

nkabrich commented Mar 28, 2013

klammbueddel commented Mar 28, 2013

A more minimalistic example to trigger the error would be to create a client and immediately close it:

I also added a log statement to your _send method in connection.js
console.log(«_send(code, more)», code, more);
This is the result:

When you send the termination signal (X) the error is raised.

klammbueddel commented Mar 28, 2013

One step further: I just tested it with all prior versions to check since when the error occured. The error comes with node-v0.9.10-x64, the changelog says:
2013.02.19, Version 0.9.10 (Unstable)

What I don’t understand is that you cant’t reproduce this one. The change should not only affect Windows systems.
I am not that familar with the TCP Commands, but regarding to
http://stackoverflow.com/questions/2974021/what-does-econnreset-mean-in-the-context-of-an-af-local-socket
the ECONNRESET implementation is kind of OS dependent.

klammbueddel commented Mar 28, 2013

nodejs/node-v0.x-archive@14a4245 fixes nodejs/node-v0.x-archive#1776
The ECONNRESET is no real «error», but applications should be able to handle it. That’s why the core team decided to bubble it up. Maybe you add some code to just ignore it?

brianc commented Mar 28, 2013

For being your first bug report you’re pretty much doing the best job ever. Thank you SO much. I don’t have easy access to a windows box these days so it’s going to be really hard for me to test this myself. You’ve gotten far enough into the code to put some log statements in the connection writer. What happens if you do this.

I am thinking this might fix. Otherwise we’ll have to temporarily bind to the error event & suppress it manually.

klammbueddel commented Mar 28, 2013

adding this.stream.end(); won’t fix it

brianc commented Mar 28, 2013

On Thu, Mar 28, 2013 at 5:28 PM, klammbueddel notifications@github.comwrote:


Reply to this email directly or view it on GitHubhttps://github.com//issues/314#issuecomment-15619219
.

brianc commented Mar 28, 2013

I guess the blanket thing to do is just handle those ECONNRESET errors from between the time we send the X packet and the socket closes

klammbueddel commented Mar 28, 2013

Sounds like a plan, can you please post a patch? Looking forward testing it.

ivanric commented Oct 19, 2016 •

This is the error console.
error fetching client from pool identificasion

Источник

Узел JS ECONNRESET

я запускаю приложение Express js с сокетом.io для чата webapp и я получаем следующую ошибку случайным образом около 5 раз во время 24 часа. Процесс узла завернут в forever и перезапускается сама немедленно.

проблема в том, что перезапуск express выбивает моих пользователей из их комнат и никто этого не хочет.

веб-сервер проксируется HAProxy. Нет проблем со стабильностью сокетов, просто используя websockets и flashsockets-транспорты. Я не могу воспроизвести это нарочно.

это ошибка с узлом v0.10.11:

EDIT (2013-07-22)

добавлены оба сокета.обработчик ошибок клиента ввода-вывода и обработчик необнаруженных исключений. Кажется, что этот ловит ошибку:

поэтому я подозреваю, что это не розетка.проблема ввода-вывода, но http-запрос на другой сервер, который я делаю, или соединение mysql/redis. Проблема в том, что стек ошибок не помогает мне идентифицировать проблему с кодом. Вот вывод журнала:

как узнать, что вызывает это? Как я могу получить больше от ошибки?

хорошо, не очень многословно, но вот stacktrace с «longjohn»:

здесь я обслуживаю файл политики flash socket:

может ли это быть причиной?

11 ответов

Вы, наверное, уже догадались: это ошибка подключения.

«ECONNRESET» означает, что другая сторона разговора TCP резко закрыла свой конец соединения. Это, скорее всего, связано с одной или несколькими ошибками протокола приложения. Вы можете посмотреть журналы сервера API, чтобы узнать, жалуется ли он на что-то.

но поскольку вы также ищете способ проверить ошибку и потенциально отладить проблему, вы должны взглянуть на «как отладить ошибку зависания сокета в NodeJS?» который был размещен в stackoverflow по отношению к аналогичному вопросу.

быстрое и грязное решение для развития:

использовать longjohn, вы получаете длинные трассировки стека, которые будут содержать асинхронные операции.

чистота и правильное решение: Технически, в узле, когда вы испускают ‘error’ событие и никто его не слушает, он бросит. Чтобы его не кинуть, поставьте на него слушателя и разберитесь с ним сами. Таким образом, вы можете зарегистрировать ошибку с дополнительной информацией.

чтобы иметь один прослушиватель для группы вызовов, вы можете использовать Домены, а также поймать другие ошибки во время выполнения. Убедитесь, что каждая асинхронная операция, связанная с http (сервер / клиент), находится в другом домен контексте по сравнению с другими частями кода, домен будет автоматически слушайте error события и будет распространять его на собственный обработчик. Таким образом, вы слушаете только этот обработчик и получаете данные об ошибках. вы также получаете больше информации бесплатно.

EDIT (2013-07-22)

«ECONNRESET» означает, что другая сторона разговора TCP резко закрыла свой конец соединения. Это, скорее всего, связано с одним или несколькими протоколами приложений ошибки. Вы можете посмотреть журналы сервера API, чтобы узнать, жалуется ли он на что-то.

что также может быть: в случайные моменты другая сторона перегружена и просто убивает соединение в результате. Если это так, зависит от того, к чему вы подключаетесь точно.

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

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *