【问题标题】:Does anyone know why this error occuring again and agian after few minutes有谁知道为什么这个错误会在几分钟后一次又一次地发生
【发布时间】:2023-05-24 04:16:01
【问题描述】:

当检测到目录中的文件更改时,我正在使用 nodemon npm 包自动重新启动节点应用程序。 服务器是使用 express 和 http npm 包创建的。 问题是当服务器空闲几分钟时它会抛出错误 Error: read ECONNRESET 实际错误如下:

events.js:167
      throw er; // Unhandled 'error' event
      ^
Error: read ECONNRESET
    at TCP.onStreamRead (internal/stream_base_commons.js:111:27)
Emitted 'error' event at:
    at Connection._handleProtocolError (/home/abc/node_modules/mysql/lib/Connection.js:425:8)
    at Protocol.emit (events.js:182:13)
    at Protocol._delegateError (/home/abc/node_modules/mysql/lib/protocol/Protocol.js:390:10)
    at Protocol.handleNetworkError (/home/abc/node_modules/mysql/lib/protocol/Protocol.js:363:10)
    at Connection._handleNetworkError (/home/abc/node_modules/mysql/lib/Connection.js:420:18)
    at Socket.emit (events.js:182:13)
    at emitErrorNT (internal/streams/destroy.js:82:8)
    at emitErrorAndCloseNT (internal/streams/destroy.js:50:3)
    at process._tickCallback (internal/process/next_tick.js:63:19)

我试图捕捉错误,但这并不能解决我的问题。

process.on('uncaughtException', function(err) {  
   console.log("uncaughtException called: \n", err);
})

使用express和http创建服务器:

express = require('express');
app = express();
http = require('http');
var httpServer = http.createServer(app);
httpServer.listen(3000, function(req, res) {
    console.log('Server running at port 3000);
});

我希望防止服务器发生 ECONNRESET 错误 解决办法是什么?

【问题讨论】:

    标签: javascript node.js npm https nodemon


    【解决方案1】:

    根据抛出的错误我们可以看出这是mysql的问题:

    Emitted 'error' event at:
    at Connection._handleProtocolError (/home/abc/node_modules/mysql/lib/Connection.js:425:8)
    

    我遇到了同样的问题,我修复它的方法是在连接到数据库后添加一个 setInterval,每 20 分钟执行一次简单查询,例如 db.query('SELECT 1;') .据说mysql会在空闲一段时间后关闭连接,所以基于post

    “模块开发人员建议使用心跳来保持连接处于活动状态,例如在间隔内调用 SELECT 1;。”

    这是一个快速修复,它对我有用,但如果你想找出不同的方法,我建议阅读上面的帖子,因为还有其他解决方案。

    【讨论】: