Put Request to Firebase with NodeJS - node.js

I am trying to make a PUT request to Firebase with NodeJS. When I make the following request, the response hangs until it times-out. No error message makes it difficult to debug--
var querystring = require('querystring');
var https = require('https');
var data = querystring.stringify({
'foo': 'bar'
});
var options = {
host: 'my-app.firebaseio.com',
port: '80',
path: '/datetimes.json?auth=password',
method: 'PUT'
var req = https.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('Response: ' + chunk);
});
});
req.write(data);
req.end();
My guess is that there is a problem with the Firebase authentication, or else I'd get an error. But this does work--
https.get({ host: 'my-app.firebaseio.com', path: '/datetimes.json?auth=password' }, function(res) {
console.log("statusCode: ", res.statusCode);
console.log("headers: ", res.headers);
res.on('data', function(d) {
process.stdout.write(d);
});
}).on('error', function(e) {
console.error(e);
});
So that makes me think maybe the password is okay and I'm just using https.request incorrectly?
[I cannot use any NPM libraries (i.e. request) because this needs to work with AWS Lambda.]

Related

NodeJS 12.x https version of a curl request on AWS Lambda

curl -d "m_payment_id=m_payment_id-xxxxxxxxxxxxxxxxxyyy&pf_payment_id=990396&payment_status=COMPLETE&item_name=Subscription&item_description=Monthly+Subscription&amount_gross=99.00&amount_fee=-6.74&amount_net=92.26&custom_str1=&custom_str2=&custom_str3=&custom_str4=&custom_str5=&custom_int1=&custom_int2=&custom_int3=&custom_int4=&custom_int5=&name_first=&name_last=&email_address=christo%40g4-ape.co.za&merchant_id=0000000&token=0000000-0000-0000-3a83-25bc733a307b&billing_date=2020-02-21&signature=3895d0769b56862b842da5067af4483f" -X POST https://sandbox.somedomain.co.za/what/something/validate
My attempt:
const https = require("https");
const querystring = "m_payment_id=m_payment_id-xxxxxxxxxxxxxxxxxyyy&pf_payment_id=990396&payment_status=COMPLETE&item_name=Subscription&item_description=Monthly+Subscription&amount_gross=99.00&amount_fee=-6.74&amount_net=92.26&custom_str1=&custom_str2=&custom_str3=&custom_str4=&custom_str5=&custom_int1=&custom_int2=&custom_int3=&custom_int4=&custom_int5=&name_first=&name_last=&email_address=christo%40g4-ape.co.za&merchant_id=0000000&token=0000000-0000-0000-3a83-25bc733a307b&billing_date=2020-02-21&signature=3895d0769b56862b842da5067af4483f";
return new Promise((resolve, reject) => {
const options = {
hostname: 'sandbox.somedomain.co.za',
port: 443,
path: 'what/something/validate',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(querystring)
}
};
const req = https.request(options, (res) => {
console.log('statusCode: ' + res.statusCode);
console.log('headers: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
console.log('BODY: ' + data);
});
resolve('Success');
});
req.on('error', (e) => {
console.log('problem with request: ' + e.message);
reject(e.message);
});
// write data to request body
req.write(querystring);
req.end();
});
I keep getting a statusCode 400 on the NodeJS code, the curl works fine. The hostname hs obviously been changed for security.
Can someone please advise me on what I'm doing wrong here?
Content-Length is reqired when you are sending the body while posting. In your case all the info is getting passed as query string parameter so you can get rid of the headers alltogather.
Also, you should be resolving inside res.on('end'. THe way you are doing it will finish the function before it even finishes execution.

Establishing a downchannel stream to alexa (AVS) using https in node js is giving parse error

I am trying to establish alexa voice downchannel stream in nodejs using https but i am getting parse error. here is the code
var https = require('https');
var fs = require('fs');
//read the accesstoken from text file.
var accessToken = fs.readFileSync('accessToken.txt','utf8');
var options = {
host: 'avs-alexa-na.amazon.com',
path: '/v20160207/directives',
scheme : 'https',
method: 'GET',
headers: {'Authorization': 'Bearer ${accessToken}'}
};
var req = https.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
req.end();
when i am running the above code, i am getting error
problem with request: Parse Error
could you please help me where i am doing mistake.

Trying to send header in node

I'm trying to access an api that requires me to send some information in the header in the GET request as described in the image below.
I have my code set up like this, but I'm getting a resp has no method setter error. I've read in various posts and seen examples in other languages where this is done, but I can't quite figure it out in node.
https.get(url, function(resp){
resp.setHeader("Content-Type", "json/application");
resp.setHeader("Authorization", Key);
resp.on('data', function(chunk){
sentStr += chunk;
});
resp.on('end', function(){
console.log(sentStr);
});
});
You are trying to set the headers for the response, while the request is the one that needs to be set. http and https takes either the URL or a set of options to start the call. here is an example
var https = require('https');
var options = {
hostname: "www.google.com",
port: 443,
path: '/',
method: 'GET',
headers: {
"Content-Type": "json/application"
"Authorization" : "KEY YOU NEED TO SUPPORT"
}
}
https.get(options, function(res) {
console.log("statusCode: ", res.statusCode);
console.log("headers: ", res.headers);
res.on('data', function(d) {
process.stdout.write(d);
});
}).on('error', function(e) {
console.error(e);
});

NodeJS HTTP Post - GZip

I have a NodeJS client that is similar to
var options = {
hostname: 'www.google.com',
port: 80,
path: '/upload',
method: 'POST'
};
var req = http.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
// write data to request body
req.write('data\n');
req.write('data\n');
req.end();
Is there any way to make the data element in the req.write gzipped at all?
To send a compressed request, compress the data into a zlib buffer, then write that as your output:
var zlib = require('zlib');
var options = {
hostname: 'www.example.com',
port: 80,
path: '/upload',
method: 'POST',
headers: {'Content-Encoding': 'gzip'} // signal server that the data is compressed
};
zlib.gzip('my data\ndata\n', function (err, buffer) {
var req = http.request(options, function(res) {
res.setEncoding('utf8');// note: not requesting or handling compressed response
res.on('data', function (chunk) {
// ... do stuff with returned data
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
req.write(buffer); // send compressed data
req.end();
});
That should send a gzipped request to the server and get a non-compressed response back. See the other answers to this question for handling a compressed response.
You can gzip a stream using the native zip library: http://nodejs.org/api/zlib.html
var zlib = require('zlib');
var gunzip = zlib.createGunzip();
var options = {
hostname: 'www.google.com',
port: 80,
path: '/upload',
method: 'POST',
headers: {'Accept-Encoding': 'gzip'}
};
var req = http.request(options);
gunzip.on('data', function (buf) {
body += buf.toString();
});
gunzip.on('end', function() {
console.log(body);
// do whatever you want to do with body
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
gunzip.end();
});
req.pipe(gunzip);
More info on zlib library: http://nodejs.org/api/zlib.html

ECONNRESET error node.js https

Guys I'm having trouble requesting to this URL.. It seems fine, but I always get the error ECONNRESET.
I wrote a little script in ruby and it worked fine. With cURL in the terminal also works.
I tried all the solutions on a lot of issues and stack overflow threads... Like these:
https://github.com/joyent/node/issues/5360
https://github.com/joyent/node/issues/5119
Any idea what it might be?
The url is: https://ecommerce.cielo.com.br/servicos/ecommwsec.do
var https = require('https');
var options = {
host: 'ecommerce.cielo.com.br',
path: '/servicos/ecommwsec.do',
//This is what changes the request to a POST request
method: 'GET',
};
https.globalAgent.options.secureProtocol = 'SSLv3_method';
callback = function(response) {
var str = ''
response.on('data', function (chunk) {
str += chunk;
});
response.on('end', function () {
console.log(str);
});
}
var req = https.request(options, callback);
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
How are you ??
Let's try this solution.
app.js
Change your options:
var options = {
host: 'ecommerce.cielo.com.br',
path:'/servicos/ecommwsec.do',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(body),
'user-agent': 'node.js'
}
};
https.globalAgent.options.secureProtocol = 'SSLv3_method';
try{
var req = https.request(options, function(res)
{
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log("body: " + chunk);
}).on('end', function(cieloResponse){
console.log( cieloResponse);
});
console.log('Response:' + res);
});
req.end();
}catch(err){
console.log('ERRO: '+ err);
}

Resources