'Error: connect ECONNREFUSED' When calling http.request - node.js

I am trying to run the following node code,
function getQuestions() {
var options = {
host: 'mysite.com',
path: '/services/v2/question.json',
headers: {
"Content-Type": "application/json",
"accept": "application/json; charset=UTF-8",
'Authorization': auth
}
};
http.request(options, function(response) {
console.log("Everything worked!");
}).on('error', function(e) {
console.log('problem with request: ' + e.stack);
});
}
But it always errors saying...
problem with request: Error: connect ECONNREFUSED
at errnoException (net.js:905:11)
at Object.afterConnect [as oncomplete] (net.js:896:19)
When I put the same info into Postman it works fine. Is there a way to debug this?
Update
Tried this...
var options = {
host: "google.com"
};
Same result so something must be wrong in my code. Any ideas?

It did end up being a proxy issue this...
var options = {
host: "proxy",
port: 80,
path: 'http://google.com'
};
Notice the proxy in host. I will mark as duplicate of this post

Related

One signal create notification REST API fails sometimes

I am using oneSignal for push notifications node.js. I am using the create notification api to send notification to the users, but i dont know why it works some times and sometimes gives timeout error
sendNotificationToUser(data) {
try {
var notificationData = {}
notificationData.app_id = oneSignalAppId
notificationData.headings = {
en: "Heading"
}
notificationData.contents = {
en: data.message
}
notificationData.include_player_ids = [data.deviceId]
var headers = {
"Content-Type": "application/json; charset=utf-8"
}
var options = {
host: "onesignal.com",
port: 443,
path: "/api/v1/notifications",
method: "POST",
headers: headers
}
var https = require("https")
var req = https.request(options, function (res) {
res.on("data", function (data1) {
console.log("Response:")
console.log(JSON.parse(data1))
})
})
req.on("error", function (e) {
console.log("ERROR:")
console.log(e)
})
req.write(JSON.stringify(notificationData))
req.end()
} catch (err) {
console.log("err in notification", err)
}
}
this api works 50% of times and 50% of times it responds with time out error, even all the inputs are correct
ERROR:
{
Error: connect ETIMEDOUT 104.18.225.52:443
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1107:14)
errno: 'ETIMEDOUT',
code: 'ETIMEDOUT',
syscall: 'connect',
address: '104.18.225.52',
port: 443
}
one simple solution is to directly hit the working ip, you can do this by including
host: 'onesignal.con' in headers and
host: '104.18.226.52' in options
this resolved my issue
to know more about how you can specify ip with host in https request
go here HTTPS request, specifying hostname and specific IP address

Node.js SSL / HTTPS request to api.bitbucket.org gets weird ssl error

I am getting this weird error:
Making request to bitbucket api at path: /2.0/repositories/interos/eco-system-globe/commit/116c82c81b8d3e1b8c2fd3f352510fd09e66a02e
***Request stream error***: Error: write EPROTO 139717438125888:error:1408F10B:SSL routines:ssl3_get_record:wrong version number:../deps/openssl/openssl/ssl/record/ssl3_record.c:332:
at WriteWrap.onWriteComplete [as oncomplete] (internal/stream_base_commons.js:83:16) {
errno: 'EPROTO',
code: 'EPROTO',
syscall: 'write'
}
the code I have is simply:
const pth = `/2.0/repositories/${fullRepoName}/commit/${sha}`;
console.log('Making request to bitbucket api at path:',pth);
const newReq = https.get({ // formerly get
protocol: 'https:',
port: 80,
hostname: 'api.bitbucket.org',
path: pth,
headers: {
'Authorization': `Basic ${bitbucketBase64}`,
'Auth': `Basic ${bitbucketBase64}`
}
}, r => {
const v = {
data: ''
};
r.on('data', d => {
v.data += String(d || '');
});
r.once('end', () => {
console.log('response ended:', r.statusCode);
cb(null, v);
});
});
newReq.once('error', e => {
console.error('***Request stream error***:', e);
});
// newReq.write(stringified);
newReq.end();
anyone have an idea what that's about? I am on Node.js version 12.2.0
I had port: 80 but it should be port: 443 ... for SSL that's the default, so you can just omit the port argument.

certificate issue in nodejs https request

I have the following error while making an https get request
{ Error: write EPROTO 101057795:error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure:openssl\ssl\s23_clnt.c:802:
at _errnoException (util.js:992:11)
at WriteWrap.afterWrite [as oncomplete] (net.js:864:14) code: 'EPROTO', errno: 'EPROTO', syscall: 'write' }
I am trying to make a request to corporate internal resource where proxy is not needed.
const request = require('request')
var token= myToken
request({
method: 'post',
url: 'https://myURL',
data: {
myData
},
headers: { 'Authorization': 'Bearer myToken' },
agentOptions: {
rejectUnauthorized: false,
},
}, function (error, response, body) {
if(error){
console.log('Error: ', error)
} else {
console.log(body)
}
})
I also have strict-ssl=false in my .npmrc.
What I have notices is that I can make the same call curl with no issues.
curl -k1 -XPOST -H "Authorization: Bearer %TOKEN%" "https://%URL% -d #data,json -H "content-type: application/json"
-k1 option in curl seems to fix the issue with the certificate.
What am I doing wrong in JavaScript?
It turned out to be a bug in node version 8. I finally found a solution here - https://github.com/nodejs/node/issues/16196
One needs to add the following into her code:
require("tls").DEFAULT_ECDH_CURVE = "auto"
request({
method: 'post',
url: 'https://myURL',
data: {
myData
},
headers: { 'Authorization': 'Bearer myToken' },
rejectUnauthorized: false,
}, function (error, response, body) {
if(error){
console.log('Error: ', error)
} else {
console.log(body)
}
});
If you don't want the TLS check all over the node project
set process.env.NODE_TLS_REJECT_UNAUTHORIZED=0;

nodeJS request POST To localhost:3000 ECONNREFUSED

At one point I just want to make a POST request to my rails server running on localhost:3000
If a use like postman on even cUrl I can ping my API
But kow, with my node app I want to do this :
var req_body = {
'my_id': id,
'dataTable': data }
var options = {
method: 'POST',
url: config.get('api_url') + 'end_tracking',
json: true,
body: req_body
}
// config.get('api_url') return http://localhost:3000/
request(options, function (error, response, body) {
console.log(error)
... }
this is what I get :
{ Error: connect ECONNREFUSED 127.0.0.1:3000
at Object.exports._errnoException (util.js:896:11)
at exports._exceptionWithHostPort (util.js:919:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1073:14)
code: 'ECONNREFUSED',
errno: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 3000 }
and as I said, if I do this request directly with postman, everything works !
I finally did it !
For a unknown reason, accessing localhost:3000, launched with rails s didn't work at all on my node server
but I worked when I started the rails server with rails s -b 0.0.0.0 !
how i did this , just use the same structure and i hope it works for you
request({
url: url, //URL to hit
method: 'post',
headers: headers,
timeout: 10000,
body: JSON.stringify(body)
}, function (error, result, body) {
if (error) {
console.log(error);
} else if (result.statusCode == 500) {
console.log('not found');
} else {
console.log('success')
}
});
hope it works.

NodeJs Error: connect ETIMEDOUT

I run node myserver.js that contains the code bellow, and after 40-50sec I get the error(bellow the code). Why do I get an error when nothing is happening?
var options = {
host: 'google.com',
port: '80',
path: '/',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': 'post_data.length'
}
};
var subscribeRequest = require('http').request(options, function(res) {
console.log('send request');
}).on('error', function(err){console.log(err.stack)});
after 40-50sec I get this error:
Error: connect ETIMEDOUT
at errnoException (net.js:904:11)
at Object.afterConnect [as oncomplete] (net.js:895:19)
I see at least two things wrong here:
You're not ending your request. When you use http.request() you have to call .end() on the request object returned when you are done sending any data so that the server knows there is no more data coming. http.get() automatically calls .end() for you because there are no bodies with GET requests.
'Content-Length': 'post_data.length' should be 'Content-Length': post_data.length
You have to call subscribeRequest.end() after declaring your request! If you don't do it, your request will never be sent

Resources