Node.js Request error - ECONNRESET - javascript

Every now and then, as I'm requesting data from a github-issue, I get this error when firing my request-promise-function:
{ RequestError: Error: read ECONNRESET
at new RequestError (/vagrant/node_modules/request-promise-core/lib/errors.js:14:15)
at Request.plumbing.callback (/vagrant/node_modules/request-promise-core/lib/plumbing.js:87:29)
at Request.RP$callback [as _callback] (/vagrant/node_modules/request-promise-core/lib/plumbing.js:46:31)
at self.callback (/vagrant/node_modules/request/request.js:187:22)
at emitOne (events.js:96:13)
at Request.emit (events.js:191:7)
at Request.onRequestError (/vagrant/node_modules/request/request.js:859:8)
at emitOne (events.js:96:13)
at ClientRequest.emit (events.js:191:7)
at TLSSocket.socketErrorListener (_http_client.js:358:9)
at emitOne (events.js:96:13)
at TLSSocket.emit (events.js:191:7)
at emitErrorNT (net.js:1283:8)
at _combinedTickCallback (internal/process/next_tick.js:80:11)
From previous event:
at Request.plumbing.init (/vagrant/node_modules/request-promise-core/lib/plumbing.js:36:28)
at Request.RP$initInterceptor [as init] (/vagrant/node_modules/request-promise-core/configure/request2.js:41:27)
at new Request (/vagrant/node_modules/request/request.js:129:8)
at request (/vagrant/node_modules/request/index.js:54:10)
at module.exports (/vagrant/resources/GetIssuesData.js:25:9)
at Socket.<anonymous> (/vagrant/app.js:42:13)
at emitNone (events.js:86:13)
at Socket.emit (events.js:188:7)
at /vagrant/node_modules/socket.io/lib/socket.js:503:12
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickCallback (internal/process/next_tick.js:104:9)
name: 'RequestError',
message: 'Error: read ECONNRESET',
cause:
{ Error: read ECONNRESET
at exports._errnoException (util.js:1029:11)
at TLSWrap.onread (net.js:575:26) code: 'ECONNRESET', errno: 'ECONNRESET', syscall: 'read' },
error:
{ Error: read ECONNRESET
at exports._errnoException (util.js:1029:11)
at TLSWrap.onread (net.js:575:26) code: 'ECONNRESET', errno: 'ECONNRESET', syscall: 'read' },
options:
{ uri: 'https://api.github.com/repos/1dv023/jp222vq-examination-3/issues?access_token=TOKEN',
headers:
{ 'User-Agent': 'me',
'Content-Type': 'application/x-www-form-urlencoded' },
simple: false,
reconnect: true,
callback: [Function: RP$callback],
transform: undefined,
resolveWithFullResponse: false,
transform2xxOnly: false },
response: undefined }
The request is fired every time a user requests a new page on the application, and is also fired when changes are made in the github-issue. The request feeds a socket-eventemitter with data. This is the request-function:
(function() {
let rp = require("request-promise");
module.exports = function(res, callback) {
let options = {
uri: "https://api.github.com/repos/" + res.issue,
headers: {
"User-Agent": "Me",
"Content-Type": "application/x-www-form-urlencoded"
},
simple: false,
reconnect: true
};
rp(options)
.then(function(body, err) {
try {
body = JSON.parse(body);
let context = {
issues: body.map(function(issue) {
return {
title: issue.title,
comments: issue.comments,
uploaded: issue.created_at,
updated: issue.updated_at,
link: "/" + issue.number
};
}),
};
callback(context, null);
} catch (e) {
throw new Error(e)
}
})
.catch(function(err) {
callback(null, err);
});
};
}());
I've been scratching my head for ages now, trying to understand why I get this error. Tried to read up on ECONNRESET, but didn't quite understand it. Can anybody please help?

Related

getaddrinfo ENOTFOUND api.telegram.org (Telegraf)

This is my code
const config = require('./config.json');
const {Telegraf} = require('telegraf');
// require('dotenv').config();
const bot = new Telegraf(config.BOT_TOKEN);
bot.use((ctx) => {
ctx.reply('Bot has started');
});
bot.launch()
every time I run this code it give me error and the error is
D:\Danish\Node testing\Node Bot Testing\node_modules\node-fetch\lib\index.js:1491
reject(new FetchError(request to ${request.url} failed, reason: ${err.message}, 'system', err));
^
FetchError: request to https://api.telegram.org/bot5121286363:[REDACTED]/getMe failed, reason: getaddrinfo ENOTFOUND api.telegram.org
at ClientRequest. (D:\Danish\Node testing\Node Bot Testing\node_modules\node-fetch\lib\index.js:1491:11)
at ClientRequest.emit (node:events:527:28)
at TLSSocket.socketErrorListener (node:_http_client:454:9)
at TLSSocket.emit (node:events:527:28)
at emitErrorNT (node:internal/streams/destroy:157:8)
at emitErrorCloseNT (node:internal/streams/destroy:122:3)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
type: 'system',
errno: 'ENOTFOUND',
code: 'ENOTFOUND'
}
[nodemon] app crashed - waiting for file changes before starting...

how to resolve ECONNRESET error in ldapjs?

I am working with LDAP JS. I am receiving ECONNRESET Error again and again, I also tried to browse it but no success. tried to add reconnect: true qualifier but no success. my code and error is as follows.
const adConfiguration = {
url: "ldap://" + process.env.ad_URL,
reconnect: true,
tlsOptions: {
rejectUnauthorized: true,
}
}
Error I am receiving is as follows:
Waiting for the debugger to disconnect...
events.js:353
throw er; // Unhandled 'error' event
^
Error: read ECONNRESET
at TCP.onStreamRead (internal/stream_base_commons.js:209:20)
at TCP.callbackTrampoline (internal/async_hooks.js:134:14)
Emitted 'error' event on Client instance at:
at Socket.onSocketError (F:\MFA\CrypLock_BE\CrypLockServer\node_modules\ldapjs\lib\client\client.js:966:12)
at Socket.emit (events.js:376:20)
at emitErrorNT (internal/streams/destroy.js:106:8)
at emitErrorCloseNT (internal/streams/destroy.js:74:3)
at processTicksAndRejections (internal/process/task_queues.js:82:21) {
errno: -4077,
code: 'ECONNRESET',
syscall: 'read'
}
[nodemon] app crashed - waiting for file changes before starting...
You need to listen for the error on your ldap client instance and handle it:
const ldapjs = require('ldapjs')
const adConfiguration = {
url: "ldap://" + process.env.ad_URL,
reconnect: true,
tlsOptions: {
rejectUnauthorized: true,
}
}
const client = ldapjs.createClient(adConfiguration)
client.on('error', (err) => {
console.log(err.message) // this will be your ECONNRESET message
})
I recommend using some sort of abstraction around your raw ldap client so when you detect the error you can reset your client appropriately.

Heroku Nodejs Reddit bot works fine locally but not online

I have a reddit bot written in Nodejs with Snoowrap and Snoostorm and deployed to Heroku.
My logs keeps churning this error out:
2020-03-13T06:02:53.784219+00:00 app[web.1]: (node:4) UnhandledPromiseRejectionWarning: RequestError: Error: ESOCKETTIMEDOUT
2020-03-13T06:02:53.784229+00:00 app[web.1]: at new RequestError (/app/node_modules/request-promise-core/lib/errors.js:14:15)
2020-03-13T06:02:53.784230+00:00 app[web.1]: at Request.plumbing.callback (/app/node_modules/request-promise-core/lib/plumbing.js:87:29)
2020-03-13T06:02:53.784231+00:00 app[web.1]: at Request.RP$callback [as _callback] (/app/node_modules/request-promise-core/lib/plumbing.js:46:31)
2020-03-13T06:02:53.784231+00:00 app[web.1]: at self.callback (/app/node_modules/request/request.js:185:22)
2020-03-13T06:02:53.784234+00:00 app[web.1]: at Request.emit (events.js:311:20)
2020-03-13T06:02:53.784234+00:00 app[web.1]: at ClientRequest.<anonymous> (/app/node_modules/request/request.js:819:16)
2020-03-13T06:02:53.784235+00:00 app[web.1]: at Object.onceWrapper (events.js:417:28)
2020-03-13T06:02:53.784235+00:00 app[web.1]: at ClientRequest.emit (events.js:311:20)
2020-03-13T06:02:53.784236+00:00 app[web.1]: at TLSSocket.emitRequestTimeout (_http_client.js:714:9)
2020-03-13T06:02:53.784237+00:00 app[web.1]: at Object.onceWrapper (events.js:417:28)
2020-03-13T06:02:53.784237+00:00 app[web.1]: at TLSSocket.emit (events.js:311:20)
2020-03-13T06:02:53.784237+00:00 app[web.1]: at TLSSocket.Socket._onTimeout (net.js:478:8)
2020-03-13T06:02:53.784238+00:00 app[web.1]: at listOnTimeout (internal/timers.js:549:17)
2020-03-13T06:02:53.784238+00:00 app[web.1]: at processTimers (internal/timers.js:492:7)
2020-03-13T06:02:53.784281+00:00 app[web.1]: (node:4) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 3)`
Here is my app.js file:
require('dotenv').config();
const MyUtil = require("./myutil.js")
const { CommentStream, SubmissionStream, ModMailStream, InboxStream } = require("snoostorm");
const Snoowrap = require('snoowrap');
const Snoostorm = require('snoostorm');
const WatchJS = require("melanke-watchjs")
const r = new Snoowrap({
userAgent: 'abcde',
clientId: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
refreshToken: process.env.REFRESH_TOKEN
});
const BOT_START = Date.now() / 1000;
var webController;
function initializeBot(controller){
configReddit();
watchRateLimit();
initCommentStream();
initPostStream();
initInboxStream();
initModMailStream();
webController = controller;
return module.exports
}
function configReddit(){
r.config({continueAfterRatelimitError: true});
console.info("Finished Reddit configuration.")
}
function watchRateLimit(){
//WATCH JS
// var watch = WatchJS.watch;
// var unwatch = WatchJS.unwatch;
// var callWatchers = WatchJS.callWatchers;
WatchJS.watch(r, "ratelimitRemaining",
() => {
if(r.ratelimitRemaining < 50){
console.warn("Rate limit remaining:" +r.ratelimitRemaining);
}
if(webController){
webController.broadcast(r.ratelimitRemaining);
}
});
}
function initCommentStream(){
console.info("Trying to establish comment stream!");
var streamOpts;
try {
streamOpts = JSON.parse(process.env.COMMENT_STREAM_OPTION);
if(!streamOpts || !streamOpts.receiving){
console.info("Comment Stream was disabled, enable through the environment variable.")
return;
}
} catch (error) {
console.log(error);
console.info("COMMENT_STREAM_OPTION unavailable/wrong format.");
return;
}
const comments = new CommentStream(r, streamOpts);
comments.on("item", comment => {
if(comment.created_utc < BOT_START) return;
if(comment.body.toLowerCase().includes("!resolved")){
console.log("New resolved comment!: "+comment.link_id.substring(3))
let flair = {flair_template_id:MyUtil.FLAIR_ID.RESOLVED}
let sub = r.getSubmission(comment.link_id.toString().substring(3));
let reply = ""; //TODO
sub.selectFlair(flair).then(sub.reply())
}
})
console.info("Comment Stream established.");
}
function initPostStream(){
console.info("Trying to establish post stream!");
var streamOpts
try {
streamOpts = JSON.parse(process.env.POST_STREAM_OPTION);
if(!streamOpts || !streamOpts.receiving){
console.info("Post Stream was disabled, enable through the environment variable.")
return;
}
} catch (error) {
console.log(error)
console.info("POST_STREAM_OPTION unavailable/wrong format.");
return;
}
const posts = new Snoostorm.SubmissionStream(r, streamOpts);
//*Listen for items (posts)
posts.on("item", post =>{
if(post.created_utc < BOT_START) return;
console.log("New POST");
console.log(post.body);
notifyNewPost("/u/abcde", post)
//TODO
})
console.info("Post Stream established!");
}
function initInboxStream(){
//TODO
}
function initModMailStream(){
//TODO
}
async function notifyNewPost(peopleList, post){
if(!post._hasFetched){
try {
post = await post.fetch();
} catch (error) {
console.log("Error at notifyNewPost")
console.log(error);
return
}
}
var sendFunction = function(people, post){
r.composeMessage({
to:people,
subject:"New post in r/GoogleAppsScript",
text:`There's a new post in r/GoogleAppsScript:
[${post.title}](${post.url}) posted by ${post.author.name}
`
}).then(()=>{console.log(`New post notification sent to ${people}.`)})
.catch((err)=>{console.log("Error on sending noti to abcde:\n"+err)});
}
if(typeof peopleList == "string"){
sendFunction(peopleList, post);
}else{
for (const people of peopleList) {
sendFunction(people, post);
}
}
}
module.exports={
initializeBot,
r
}
This is web.js:
const controller = {};
var express = require('express');
var app = express();
const wakeDyno = require("woke-dyno");
const bot = require("./app").initializeBot(controller);
var http = require('http').createServer(app);
var io = require('socket.io')(http);
var port = process.env.PORT || 3000;
app.get('/', function(req, res){
res.sendFile(__dirname + '/html/index.html');
});
io.on('connection', function(socket){
console.log('a user connected');
});
http.listen(port, ()=>{
wakeDyno("https://gas-lighter-bot.herokuapp.com/").start();
console.log('listening on *:'+port);
});
controller.broadcast = (msg) => {
io.emit("ratelimitChanged",msg);
};
The weird thing is the log don't tell me where the error originated in my code, so I am a bit clueless.
I've been running it for a few hours on my machine, but when deployed to Heroku, it throw this error after like 1 minute....
Please help :(
EDIT: This is the error object, it doesn't help me, but maybe it will help you solve this :(
{
name: 'RequestError',
message: 'Error: ESOCKETTIMEDOUT',
cause: Error: ESOCKETTIMEDOUT
at ClientRequest.<anonymous> (/app/node_modules/request/request.js:816:19)
at Object.onceWrapper (events.js:417:28)
at ClientRequest.emit (events.js:311:20)
at TLSSocket.emitRequestTimeout (_http_client.js:714:9)
at Object.onceWrapper (events.js:417:28)
at TLSSocket.emit (events.js:311:20)
at TLSSocket.Socket._onTimeout (net.js:478:8)
at listOnTimeout (internal/timers.js:549:17)
at processTimers (internal/timers.js:492:7) {
code: 'ESOCKETTIMEDOUT',
connect: false
},
error: Error: ESOCKETTIMEDOUT
at ClientRequest.<anonymous> (/app/node_modules/request/request.js:816:19)
at Object.onceWrapper (events.js:417:28)
at ClientRequest.emit (events.js:311:20)
at TLSSocket.emitRequestTimeout (_http_client.js:714:9)
at Object.onceWrapper (events.js:417:28)
at TLSSocket.emit (events.js:311:20)
at TLSSocket.Socket._onTimeout (net.js:478:8)
at listOnTimeout (internal/timers.js:549:17)
at processTimers (internal/timers.js:492:7) {
code: 'ESOCKETTIMEDOUT',
connect: false
},
options: {
gzip: true,
json: true,
headers: { 'user-agent': 'myuseragent' },
baseUrl: 'https://oauth.reddit.com',
qs: { raw_json: 1 },
auth: { bearer: 'myrefreshtoken' },
resolveWithFullResponse: true,
timeout: 5000,
transform: [Function: transform],
uri: 'comments/fhxl4r',
method: 'GET',
callback: [Function: RP$callback],
simple: true,
transform2xxOnly: false
},
response: undefined
}

Node.js MSSQL 500: Internal Error. Details: ConnectionError: Failed to connect to DESKTOP-LK9JDJJ:1433 - connect ECONNREFUSED 192.168.99.1:1433

settings.js
exports.dbConfig = {
user: "gpolat",
password: "alphalpha",
server: "DESKTOP-LK9JDJJ",
database: "mydemo",
port: 1433
};
exports.webPort = 9000;
db.js
var sqlDb = require("mssql");
var settings = require("../settings");
exports.executeSql = function (sql, callback) {
var conn = new sqlDb.Connection(settings.dbConfig);
conn.connect()
.then(function () {
var req = new sqlDb.Request(conn);
req.query(sql)
.then(function (recordset) {
callback(recordset);
})
.catch(function (err) {
console.log(err);
callback(null, err);
});
})
.catch(function (err) {
console.log(err);
callback(null, err);
});
};
Console Error:
Debugger listening on 127.0.0.1:5858
Started Listening at: 9000
{ ConnectionError: Failed to connect to DESKTOP-LK9JDJJ:1433 - connect
ECONNREFUSED 192.168.99.1:1433
at Connection.<anonymous> (C:\Users\Gokhan\documents\visual studio
2015\Projects\SampleREST\SampleREST\node_modules\mssql\lib\tedious.js:378:25)
at Object.onceWrapper (events.js:290:19)
at emitOne (events.js:96:13)
at Connection.emit (events.js:188:7)
at Connection.socketError (C:\Users\Gokhan\documents\visual studio
Projects\SampleREST\SampleREST\node_modules\tedious\lib\connection.js:531:1
4)
at emitOne (events.js:96:13)
at Socket.emit (events.js:188:7)
at emitErrorNT (net.js:1281:8)
at _combinedTickCallback (internal/process/next_tick.js:74:11)
at process._tickCallback (internal/process/next_tick.js:98:9)
name: 'ConnectionError',
message: 'Failed to connect to DESKTOP-LK9JDJJ:1433 - connect ECONNREFUSED
192.168.99.1:1433',
code: 'ESOCKET' }
I get this error while creating the rest API via sql server.
"500: Internal Error. Details: ConnectionError: Failed to connect to DESKTOP-LK9JDJJ:1433 - connect ECONNREFUSED 192.168.99.1:1433"

mailchimp unsubscribe with node js server

i have a problem with mailchimp unsubscribe process.
Please can you provide me the way for unsubscribe process. How exactly put in unsubscribe list and what files i should request. And how i know the differences that the email should be put in unsubscribe list.
mailchimp.post('/lists/{id}', {
email_address : "email#email.com"
})
.then(function(results) {
console.log(results)
})
.catch(function (err) {
console.log(err)
});
Response error
{ Error: The resource submitted could not be validated. For field-specific details, see the 'errors' array.
at Request._callback (/Users/Gizbreht/Desktop/myofer-mailer-express/node_modules/mailchimp-api-v3/index.js:506:30)
at Request.self.callback (/Users/Gizbreht/Desktop/myofer-mailer-express/node_modules/request/request.js:187:22)
at emitTwo (events.js:106:13)
at Request.emit (events.js:191:7)
at Request.<anonymous> (/Users/Gizbreht/Desktop/myofer-mailer-express/node_modules/request/request.js:1126:10)
at emitOne (events.js:96:13)
at Request.emit (events.js:188:7)
at IncomingMessage.<anonymous> (/Users/Gizbreht/Desktop/myofer-mailer-express/node_modules/request/request.js:1046:12)
at IncomingMessage.g (events.js:291:16)
at emitNone (events.js:91:20)
at IncomingMessage.emit (events.js:185:7)
at endReadableNT (_stream_readable.js:974:12)
at _combinedTickCallback (internal/process/next_tick.js:74:11)
at process._tickCallback (internal/process/next_tick.js:98:9)
type: 'http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/',
title: 'Invalid Resource',
status: 400,
detail: 'The resource submitted could not be validated. For field-specific details, see the \'errors\' array.',
instance: '',
errors:
[ { field: '',
message: 'Required fields were not provided: members' } ] }
mailchimp.post('/lists/{id}', {
"members" : [{"email_address": email, "status": "unsubscribed"}],"update_existing":true
})
.then(function(results) {
console.log(results)
})
.catch(function (err) {
console.log(err)
});

Categories

Resources