Error connect ECONNREFUSED - javascript

I'm getting this error and unable to fix this.
events.js:72
throw er; // Unhandled 'error' event
^
Error: connect ECONNREFUSED
at errnoException (net.js:901:11)
at Object.afterConnect [as oncomplete] (net.js:892:19)
var http = require('http');
var options = {
host: 'localhost',
port: '8081',
path: '/index.htm'
};
var callback = function(response){
var body = '';
response.on('data', function(data) {
body += data;
});
response.on('end', function() {
console.log(body);
});
}
var req = http.request(options, callback);
req.end();

Related

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
}

nodejs events.js:141 unhandled error event ETIMEDOUT

I have a Heroku server with node.js and express that pings a website's API every second. This works fine for hours at a time, but every once in a while I'll get this error:
2018-01-10T02:19:28.579566+00:00 app[web.1]: events.js:141
2018-01-10T02:19:28.579578+00:00 app[web.1]: throw er; // Unhandled 'error' event
2018-01-10T02:19:28.579579+00:00 app[web.1]: ^
2018-01-10T02:19:28.579581+00:00 app[web.1]:
2018-01-10T02:19:28.579582+00:00 app[web.1]: Error: connect ETIMEDOUT 45.60.11.241:443
2018-01-10T02:19:28.579583+00:00 app[web.1]: at Object.exports._errnoException (util.js:907:11)
2018-01-10T02:19:28.579584+00:00 app[web.1]: at exports._exceptionWithHostPort (util.js:930:20)
2018-01-10T02:19:28.579585+00:00 app[web.1]: at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1078:14)
2018-01-10T02:19:28.684990+00:00 heroku[web.1]: Process exited with status 1
Sometimes the error is ETIMEDOUT but sometimes it's other things (can't remember right now).
Some other post I read made me think maybe this is a problem?
app.listen(app.get('port'), function() {
console.log("Node app is running at localhost:" + app.get('port'))
})
Or maybe it's the part inside the API call loop?
try
{
async.series([
function(callback) {
apiQuery( callback, method, params);
},
], function(error, results) {
console.log(results)
});
}
catch(e)
{
console.log("something went wrong!")
}
Not sure why the try catch isn't catching the error if it's this.
Maybe it's how I'm starting the loop?
runLoop()
//start looping the api data pulls
function runLoop() {
setInterval(apiLoop, 1000)
}
Would it be better to have apiLoop call itself in the callback function? Or would that create nested functions that keep using increasingly larger memory?
Here is the api call code:
function apiQuery( callback2, method, params )
{
if ( ! params ) params = [];
var host_name = 'www.host.com';
var url = '/Api/' + method;
if ( params ) url += "/" + params.join('/');
var options = {
host: host_name,
path: url,
};
callback = function(response) {
var str = '';
response.on('data', function (chunk) {
str += chunk;
});
response.on('end', function () {
return callback2(null, str);
});
}
https.request(options, callback).end();
}
Maybe ETIMEOUT is caused by the website's server, anyway you can catch the error
const req = https.request(options, callback)
req.on('error', (e) => {
console.error(e);
});
req.end();

ECONNREFUSED when starting node express application

events.js:141
throw er; // Unhandled 'error' event
^
Error: connect ECONNREFUSED 127.0.0.1:4562
at Object.exports._errnoException (util.js:837:11)
at exports._exceptionWithHostPort (util.js:860:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1060:14)
here is my code
var express = require('express');
var net = require('net');
var app = express();
var i = 0;
app.get('/', function (req, res)
{
i = i+1; //no of clinets request gin ne ki liye
console.log(i + "fa..sa");
var client = net.connect({port: 4562},"192.168.202.101", function() {
console.log('connected to server!'); });
client.write("Ho gaya bhai");
client.end();
res.send('ho gaya bhai..');
});
app.listen(6544);
As you can see from your error message you have an error in the way you call net.connect. It looks like you want to connect to 192.168.202.101:4562, but you try to connect to ´127.0.0.1:4562´. Try either:
net.connect({ port: 4562, host: "192.168.202.101"}, function(){});
or:
net.connect(4562, "192.168.202.101", function() {});

https.request to wikipedia page - not found error.

In this code I want to create a request object to download a wikipedia page.
This is how I tried to do it:
var https = require('https');
var fs = require('fs');
var options = {
hostname: 'en.wikipedia.org/',
port: 443,
path: '/wiki/George_Washington'
};
var req = https.request(options, function(res) {
var responseBody = "";
res.setEncoding("UTF-8");
res.on('data', function(chunk) {
responseBody += chunk;
});
res.on('end', function() {
fs.writeFile('wikipedia.md', responseBody, function(err) {
if(err) {
throw err;
}
});
});
});
req.on('error', function(err) {
if(err) {
console.log('Problem with request ', err);
}
});
req.end();
But i received the following error:
Problem with request { [Error: getaddrinfo ENOTFOUND en.wikipedia.org/ en.wikipedia.org/:443]
code: 'ENOTFOUND',
errno: 'ENOTFOUND',
syscall: 'getaddrinfo',
hostname: 'en.wikipedia.org/',
host: 'en.wikipedia.org/',
port: 443 }
Could it be that I got the wrong port number? Or somthing is wrong with my routes?
Your hostname:
hostname: 'en.wikipedia.org/',
contains a trailing slash. Remove it:
hostname: 'en.wikipedia.org',
and your code works fine.

How to make a https request in node.js

I need to make a crawler. For http request i used to do this.
var http=require('http');
var options={
host:'http://www.example.com',
path:'/foo/example'
};
callback=function(response){
var str='';
response.on('data',function(chunk){
str+=chunk;
});
response.on('end', function () {
console.log(str);
});
}
http.request(options, callback).end();
but I have to make a crawler for https://example.com/foo/example
If I am using the same for https://example.com/foo/example it is giving this error
events.js:72
throw er; // Unhandled 'error' event
^
Error: getaddrinfo ENOTFOUND
at errnoException (dns.js:37:11)
at Object.onanswer [as oncomplete] (dns.js:124:16)
I'd recommend this excellent HTTP Request module: http://unirest.io/nodejs.html
You can install it with:
npm install -g unirest
Here's some example Node code with Unirest:
var url = 'https://somewhere.com/';
unirest.get(url)
.end(function(response) {
var body = response.body;
// TODO: parse the body
done();
});
...so to get the HTML at www.purple.com you'd do this:
#!/usr/bin/env node
function getHTML(url, next) {
var unirest = require('unirest');
unirest.get(url)
.end(function(response) {
var body = response.body;
if (next) next(body);
});
}
getHTML('http://purple.com/', function(html) {
console.log(html);
});

Categories

Resources