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();
Related
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?
const options = {
hostname: 'https://vision.googleapis.com/v1/images:annotate?key=<some key>',
method: 'POST',
headers: {
'Content-Type' : 'application/json'
}
};
const req = http.request(options, (res : any) => {
res.on('data', (chunk : any) => {
console.log(`BODY: ${chunk}`);
});
});
req.on('error', (e) => {
console.log(e)
console.error(`problem with request: ${e.message}`);
});
// Write data to request body
req.write(JSON.stringify(body))
req.end()
I am trying to use one of the google vision feature i.e. Text Detection. But when ever I am hitting that api I am getting this error. I double checked the url and other data.
{ Error: getaddrinfo ENOTFOUND https://vision.googleapis.com/v1/images:annotate?key=<> https://vision.googleapis.
com/v1/images:annotate?key=<key>:80
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:56:26)
errno: 'ENOTFOUND',
code: 'ENOTFOUND',
syscall: 'getaddrinfo',
hostname:
'https://vision.googleapis.com/v1/images:annotate?key=<key>',
host:
'https://vision.googleapis.com/v1/images:annotate?key=<key>',
port: 80 }
This code should work, there are only a couple of changes necessary, for example we'll use the https module rather than the http module.
const https = require('https');
const options = {
hostname: 'vision.googleapis.com',
path: '/v1/images:annotate?key=' + API_KEY,
method: 'POST',
headers: {
'Content-Type' : 'application/json'
}
};
let data = "";
const req = https.request(options, (res: any) => {
res.on('data', (chunk: any) => {
data += chunk;
});
res.on('end', (chunk) => {
console.log(`BODY: ${data}`);
});
});
req.on('error', (e) => {
console.log(e)
console.error(`problem with request: ${e.message}`);
});
// Write data to request body
req.write(JSON.stringify(body))
req.end()
Try modifying the request to:
const options = {
method: 'POST',
headers: {
'Content-Type' : 'application/json'
}
};
const req = http.request(`https://vision.googleapis.com/v1/images:annotate?key=<some key>`, options, (res : any) => {
res.on('data', (chunk : any) => {
console.log(`BODY: ${chunk}`);
});
});
because https://vision.googleapis.com/v1/images:annotate?key=<some key> is a full URL, not a valid hostname.
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?
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 ?
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.