Firebase Cloud Functions Error: connect ECONNREFUSED - node.js

I am trying to create a Kik Messenger bot according to their API using Firebase Cloud Functions. I am using Blaze Plan. I am trying to reply to a message that my bot received. I can receive messages on my API but when I try to reply to them I get an error. An error is not from the request callback. I see the error on Firebase Console.
Error: connect ECONNREFUSED 72.14.246.44:443
at Object.exports._errnoException (util.js:1018:11)
at exports._exceptionWithHostPort (util.js:1041:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1086:14)
code: 'ECONNREFUSED',
errno: 'ECONNREFUSED',
syscall: 'connect',
address: '72.14.246.44',
port: 443
Requests to the Kik Messenger API works on local and remote node/express app. I tried to use kik-node on Cloud Functions but it gave the same result. What I have discovered so far is that https://auth.kik.com resolves to Amazon and https://api.kik.com resolves to Google Hosting. I think they are also using Firebase Cloud Functions for their API. Can it be possible that they are blocked inbound requests? Here is the sample code of what I tried.
exports.messagepost = functions.https.onRequest((req, res) => {
// Gives the error below
// {
// Error: connect ECONNREFUSED 72.14.246.44:443
// at Object.exports._errnoException (util.js:1018:11)
// at exports._exceptionWithHostPort (util.js:1041:20)
// at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1086:14)
// code: 'ECONNREFUSED',
// errno: 'ECONNREFUSED',
// syscall: 'connect',
// address: '72.14.246.44',
// port: 443
// }
request.post({
uri: 'https://api.kik.com/v1/message',
body: JSON.stringify({
foo: 'bar'
}),
json: true,
auth:{
user:'{API_USER}',
pass:'{API_KEY}'
},
headers: {
'Content-Type' : 'application/json'
}
}, (error, response) => {
if (error) console.error(error);
else console.log('Response: ', response.headers);
res.status(200).end('OK');
});
});
exports.messageget = functions.https.onRequest((req, res) => {
// Gives the error below
// {
// Error: connect ECONNREFUSED 72.14.246.44:443
// at Object.exports._errnoException (util.js:1018:11)
// at exports._exceptionWithHostPort (util.js:1041:20)
// at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1086:14)
// code: 'ECONNREFUSED',
// errno: 'ECONNREFUSED',
// syscall: 'connect',
// address: '72.14.246.44',
// port: 443
// }
request.get({
uri: 'https://api.kik.com/v1/message',
auth:{
user:'{API_USER}',
pass:'{API_KEY}'
}
}, (error, response) => {
if (error) console.error(error);
else console.log('Response: ', response.headers);
res.status(200).end('OK');
});
});
exports.verificationget = functions.https.onRequest((req, res) => {
// Runs with no errors
request.get({
uri: 'https://auth.kik.com/verification/v1/check',
qs: {
u: 'username',
d: 'hostname',
debug: true
},
body: JSON.stringify({ data: 'debugsigneddata' }),
headers: {
'Content-Type' : 'application/json' ,
'Content-Length' : JSON.stringify({ data: 'debugsigneddata' }).length
},
auth:{
user:'{API_USER}',
pass:'{API_KEY}'
}
}, (error, response) => {
if (error) console.error(error);
else console.log('Response: ', response.headers);
res.status(200).end('OK');
});
});
exports.verificationpost = functions.https.onRequest((req, res) => {
// Runs with no errors
request.post({
uri: 'https://auth.kik.com/verification/v1/check',
qs: {
u: 'username',
d: 'hostname',
debug: true
},
body: JSON.stringify({ data: 'debugsigneddata' }),
headers: {
'Content-Type' : 'application/json' ,
'Content-Length' : JSON.stringify({ data: 'debugsigneddata' }).length
},
auth:{
user:'{API_USER}',
pass:'{API_KEY}'
}
}, (error, response) => {
if (error) console.error(error);
else console.log('Response: ', response.headers);
res.status(200).end('OK');
});
});

I ran into a similar issue while implementing an OAuth2 token exchange using cloud functions instead of running a dedicated server.
This might not help the OP but to fix this error in my case, I had to add the https:// protocol to my post URL as it was missing.
If others run into this issue it might be worth checking your POST url is written correctly.

Related

arangojs collections() errors return

I'm totally green with it all. Sorry, but I cant get this thing to work at all node.js + arangojs >
const myColl = async () => {//new Promise((resolve, reject) => {
try {
const db = await new Database({
url: "http://localhost:8529",
databaseName: "testDB",
auth: {username: "userTest", password: "userTest"},
});
console.log(db)
try {
let collection = await db.collections();
console.log(collection);
} catch (err) {
console.log(err);
}
} catch (err) {
console.log("Failed to login db ", err)
return
}
}
myColl()
I just end up with :
Database {_analyzers: Map(0), _collections: Map(0), _graphs: Map(0), _views: Map(0), _connection: Connection, ...}
icAccountController.js:23
Error: connect ECONNREFUSED ::1:8529 at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1237:16) at TCPConnectWrap.callbackTrampoline (node:internal/async_hooks:130:17) {errno: -4078, code: "ECONNREFUSED", syscall: "connect", address: "::1", port: 8529, ...}

nodejs equivalent of https curl -k request

I was following the guide here https://www.elastic.co/guide/en/cloud-on-k8s/current/k8s-deploy-elasticsearch.html for accessing elasticsearch via a curl request and was wondering how I can translate this curl -u "elastic:somepassword" -k "https://quickstart-es-http:9200" to nodejs.
I have this setup but I'm unable to connect:
https.get(
"https://quickstart-es-http:9200",
{ headers: { authorization: "Basic elastic:" + process.env.ES_SECRET } },
(innerRes) => {
let data = "";
innerRes.on("error", (err) => {
console.error("erro>>", err);
});
innerRes.on("data", (chunk) => {
data += chunk;
});
innerRes.on("end", () => {
console.log("data", data);
res.send(data);
});
innerRes.on("close", () => {
console.log("data", data);
res.send(data);
});
}
);
the error message I'm getting is:
Error: connect ECONNREFUSED 10.28.9.116:9200
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1133:16)
Emitted 'error' event on ClientRequest instance at:
at TLSSocket.socketErrorListener (node:_http_client:447:9)
at TLSSocket.emit (node:events:365:28)
at emitErrorNT (node:internal/streams/destroy:193:8)
at emitErrorCloseNT (node:internal/streams/destroy:158:3)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
errno: -111,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '10.28.9.116',
port: 9200
}
Thank you!
You can set rejectUnauthorized to false. See more here https://nodejs.org/api/https.html#https_https_request_url_options_callback
const https = require('https');
const options = {
hostname: 'encrypted.google.com',
port: 443,
path: '/',
method: 'GET',
rejectUnauthorized: false
};
const req = https.request(options, (res) => {
console.log('statusCode:', res.statusCode);
console.log('headers:', res.headers);
res.on('data', (d) => {
process.stdout.write(d);
});
});
req.on('error', (e) => {
console.error(e);
});
req.end();

Missing credentials in config, if using AWS_CONFIG_FILE, set AWS_SDK_LOAD_CONFIG=1 node.js

Trying to connect to DynamoDB and getting this error
I am trying to use this db to test some Telegram bots but now its not essential, cause i just can't find any information how to fix this problem, mb i am stupid, but...
Code:
var AWS = require("aws-sdk");
let awsConfig = {
"region": "eu-central-1",
"endpoint": "http://dynamodb.eu-central-1.amazonaws.com",
"accessKeyId": "my_access_key",
"secretAccesKey": "my_secret_access_key"
}
AWS.config.update(awsConfig);
let docClient = new AWS.DynamoDB.DocumentClient();
let fetchOneByKey = function ()
{
var params =
{
TableName: "users",
Key: {
"id": 132
}
};
docClient.get(params, function (err, data) {
if(err){
console.log("error: " + JSON.stringify(err, null, 2));
}
else
{
console.log("success: " + JSON.stringify(data, null, 2));
}
})
}
fetchOneByKey();
Tried some solutions from here, but nothing helped
Tried another solution:
let db = new AWS.DynamoDB({apiVersion: '2014-12-04'});
db.listTables({}, function(err, data) { // 2
console.log(data);
console.log(err);
});
Catched this
data:
null
err:
Error: connect ENETUNREACH 169.254.169.254:80
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1146:16) {
message: 'Missing credentials in config, if using AWS_CONFIG_FILE, set AWS_SDK_LOAD_CONFIG=1',
errno: -4062,
code: 'CredentialsError',
syscall: 'connect',
address: '169.254.169.254',
port: 80,
time: 2021-04-15T23:15:09.312Z,
originalError: {
message: 'Could not load credentials from any providers',
errno: -4062,
code: 'CredentialsError',
syscall: 'connect',
address: '169.254.169.254',
port: 80,
time: 2021-04-15T23:15:09.312Z,
originalError: {
message: 'EC2 Metadata roleName request returned error',
errno: -4062,
code: 'ENETUNREACH',
syscall: 'connect',
address: '169.254.169.254',
port: 80,
time: 2021-04-15T23:15:09.312Z,
originalError: [Object]
}
}
}

How to use https module with uri?

I am trying to use native https module in nodejs.
The code sample below works fine with request-promise-native library
var apiver = '2017-09-01';
var resource = 'https://management.azure.com/';
const rp = require('request-promise-native');
var options = {
uri: `${process.env["MSI_ENDPOINT"]}/?resource=${resource}&api-version=${apiver}`,
headers: {
'Secret': process.env["MSI_SECRET"]
}
};
return rp(options);
Here the uri = "http://127.0.0.1:41437/MSI/token//?resource=https://management.azure.com/&api-version=2017-09-01"
But if I try to do the same thing using https module it throws error
return new Promise( (resolve,reject) => {
var apiver = '2017-09-01';
var resource = 'https://management.azure.com/';
var options = {
"method": "GET",
"hostname": "localhost",
"port": 41437,
"protocol": "https:",
"path": `/MSI/token/?resource=${resource}&api-version=${apiver}`,
headers: {
'Secret': process.env["MSI_SECRET"]
}
};
var req = https.request(options, function (res) {
var body = '';
res.setEncoding('utf8');
res.on('data', function (chunk) {
body += chunk;
});
res.on('end', function () {
if (res.statusCode == 200) {
resolve(body);
} else {
reject({'error':null,'res':res});
}
});
});
req.on('error', function (e) {
reject({'error':e,'res':null});
});
req.end();
});
Following error is thrown
{
hostname: 'localhost',
port: 41437,
protocol: 'https:',
path: '/MSI/token/?resource=https://management.azure.com/&api-version=2017-09-01',
headers: { Secret: '41A1BDD07D4B42159F71353FCCE2F0EB' } }
2018-10-05T11:36:12.395 [Info] { error: {
Error: connect EACCES 127.0.0.1:41437
at Object.exports._errnoException (util.js:1020:11)
at exports._exceptionWithHostPort (util.js:1043:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1086:14)
code: 'EACCES',
errno: 'EACCES',
syscall: 'connect',
address: '127.0.0.1',
port: 41437
},
res: null
}
Is it not possible to do this request with native https module?

NodeJS { [Error: socket hang up] code: 'ECONNRESET' }

I use Node v0.12.18 and Express v4, and for one POST request, I got this error :
{ [Error: socket hang up] code: 'ECONNRESET' }
Error: socket hang up
at createHangUpError (_http_client.js:215:15)
at Socket.socketOnEnd (_http_client.js:300:23)
at Socket.emit (events.js:129:20)
at _stream_readable.js:908:16
at process._tickDomainCallback (node.js:381:11)
With this code :
optionsYoutube = {
host: dostsub_host,
port: 80,
path: '/api/media/'+ uuid +'/youtube/push',
method: 'POST',
timeout: 1200000, //20 min
headers: {
'Authorization': auth
}
};
console.log('TRY > Youtube');
var postYoutube = http.request(optionsYoutube, function(json) {
json.on('data', function(d) {
body += d;
});
json.on('end', function() {
.....
}).on('error', function(err) {
console.log(err);
return next(err);
});
I try to use this API : https://dotsub.com/apidoc/api#youtube
I looked that can be a problem of timeout, so I set in my app.js :
// set timeout
var timeout = require('connect-timeout');
app.use(timeout(1200000));
app.use(haltOnTimedout);
function haltOnTimedout(req, res, next){
if (!req.timedout) next();
}
But it changed nothing. How can I have more informations on the error ?

Resources