NodeJS { [Error: socket hang up] code: 'ECONNRESET' } - node.js

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 ?

Related

Error: socket hang up - Lambda nodejs function http post request

I have a very simple function in Lambda using Nodejs.
The purpose of that function is to triggered a third party api every 1 minute.
So for that I have setup Cloud Watch Cron based event.
But that Api is throwing this error:
START RequestId: 54d90c9d-0a5b-4e5e-a26a-857d9bb6dd4e Version: $LATEST
2022-08-29T11:11:59.112Z 54d90c9d-0a5b-4e5e-a26a-857d9bb6dd4e ERROR Error: socket hang up
at connResetException (node:internal/errors:692:14)
at TLSSocket.socketOnEnd (node:_http_client:478:23)
at TLSSocket.emit (node:events:539:35)
at endReadableNT (node:internal/streams/readable:1345:12)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
code: 'ECONNRESET'
It works fine in a simple nodejs code on my local machine.
Here is my Lambda Function code:
const https = require('https');
exports.handler = async (event) => {
var postData = JSON.stringify({
"client_id": "abnbfye9-qtfnf1cj-abhrhzfyf7-m2tup-6x9kk2kc5688",
"client_secret": "fpghfh329-polk80s-ye043465p1yy-45hxnfd874z06",
"inTime": new Date(),
"outTime": new Date()
});
var options = {
hostname: 'example.com',
path: '/api/updateDataLambda',
method: 'POST',
port: 443, // 👈️ replace with 80 for HTTP requests
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiJ0ekpFTlNxcDJXeXh4YlNGbSIsImFjY2Vzc1Rva2VuRXhwIjp7ImRhdGUiOiIyMDIyLTA5LTI4IiwidGltZSI6IjA2OjIwOjQ1IiwidGltZVN0YW1wIjoxNjY0MzQ2MDQ1NjQ2LCJnbXQiOiIrMDAwMCJ9LCJyZWZyZXNoVG9rZW5FeHAiOnsiZGF0ZSI6IjIwMjItMDktMjgiLCJ0aW1lIjoiMDY6MjA6NDUiLCJ0aW1lU3RhbXAiOjE2NjQzNDYwNDU2NDYsImdtdCI6IiswMDAwIn0sImlhdCI6MTY2MTc1NDA0NSwiZXhwIjoxNjYxNzU0MTA1fQ.g1e5S15Q1qxB5_s4j3LFfFf6spU8gwgBUyVNLVuWNWk'
}
};
var 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.write(postData);
req.end();
const response = {
statusCode: 200,
body: JSON.stringify('Hello from Lambda!'),
};
return response;
};
Am I doing something wrong here?

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();

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?

Error with request.js when trying to download a file larger than about 256MB

Using request JS as part of our artifact handler and since the artifact has been increased drastically I keep getting this error when trying to download it:
End of download
buffer.js:556
if (encoding === undefined) return buf.utf8Slice(start, end);
^
Error: "toString()" failed
at stringSlice (buffer.js:556:42)
at Buffer.toString (buffer.js:633:10)
at Request.<anonymous> (/node_modules/request/request.js:1137:39)
at emitOne (events.js:121:20)
at Request.emit (events.js:211:7)
at IncomingMessage.<anonymous>
(node_modules/request/request.js:1085:12)
at Object.onceWrapper (events.js:313:30)
at emitNone (events.js:111:20)
at IncomingMessage.emit (events.js:208:7)
at endReadableNT (_stream_readable.js:1055:12)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickCallback (internal/process/next_tick.js:180:9)
I have seen a few threads about this most specifically here: https://github.com/request/request/issues/2826
I pasted the chunk of code it is having issues with. Anyone see anything not right some advice would be welcome
function downloadArtifact(options) {
return new Promise((resolve, reject) => {
log('\nDownloading artifact from bamboo');
if (options.skip.downloadArtifact) {
log("Skipping");
return resolve(options);
}
const planKey = options.branch.planKey;
const buildNumber = options.latestBuild.number;
const artifactName = options.bamboo.artifactName;
const destinationDir = options.artifact.directory;
const downloadUrl = options.bamboo.downloadUrl;
const username = options.bamboo.username;
const password = options.bamboo.password;
const tmpFilePath = options.tmpFilePath;
const requestOptions = {
gzip: true,
timeout: 15000,
time: true,
followRedirect: true,
uri: downloadUrl,
qs: {
os_authType: 'basic',
planKey: planKey,
buildNumber: buildNumber,
artifactName: artifactName
},
headers: {
'Accept': 'application/octet-stream'
}
};
request
.get(downloadUrl, requestOptions, downloadArtifactCallback)
.auth(username, password)
.on('data', (data) => {
process.stdout.write('.');
})
.on('end', () => {
log('\nEnd of download');
})
.on('error', function(err) {
console.log(err)
})
.pipe(fs.createWriteStream(tmpFilePath));
function downloadArtifactCallback(err, res, body) {
log('\nDownload artifact callback');
if (err) {
const error = {
error: err,
headers: res && res.headers,
message: 'Error on the download'
};
return reject(error);
}
log(`Headers: ${stringify(res.headers)}`);
log(`Elapsed Time (ms): ${res['elapsedTime']}`);
// get file name from header
let fileName;
try {
const contentDispositionHeader = res.headers[constants.headers.CONTENT_DISPOSITION];
const parsedContentDisposition = contentDisposition.parse(contentDispositionHeader);
fileName = parsedContentDisposition['parameters'].filename;
} catch (e) {
const error = {
error: e.message,
message: 'Most likely tried to download a web page'
};
return reject(error);
}
// rename the file
const destinationPath = `${destinationDir}/${fileName}`;
options.artifact.fileName = fileName;
options.artifact.path = destinationPath;
try {
shell.mv(tmpFilePath, destinationPath);
} catch (err) {
return reject(err);
}
log(green('\nLeaving download artifact callback'));
return resolve(options)
}
});
}
And yes before anyone says there are similar questions I have looked at all those and after 8 hours my head hurts and no success. :)

Firebase Cloud Functions Error: connect ECONNREFUSED

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.

Resources