Trying to send header in node - node.js

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

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.

node.js https.get() res confusion between header and body

I recently start learning node.js,
In node.js https module I make a server request with https.get(); and i console.dir(res.header) this give me the response header, but when I try to console.dir(res.body) this give me undefined;
I did some investigation on the internet, and I have seen that I need to call data event to log the body. It's make me confused, why can't I log body directly, and the data format for header is string and for body is buffer?
Here are some examples of using the https.request method (same as get), they should show you some ways to use the method. These examples use the httpbin.org site, a very useful one for playing around with this kind of code.
const https = require ('https');
// Example 1
// This will return the IP address of the client
var request = https.request({ hostname: "httpbin.org", path: "/ip" }, (res) => {
console.log('/ip', res.statusCode);
res.on('data', (d) => {
console.log('/ip response: ', d.toString());
});
});
request.on('error', (e) => {
console.log(`problem with request: ${e.message}`);
});
request.end();
// Example 2
// This will return some simple data about the get request
request = https.request({ hostname: "httpbin.org", path: "/get"}, (res) => {
console.log('/get', res.statusCode);
res.on('data', (d) => {
console.log('/get response: ', d.toString());
});
});
request.on('error', (e) => {
console.log(`problem with request: ${e.message}`);
});
request.end();
// Example 3
var data = JSON.stringify({firstName: 'Mike', secondName: 'Jones'});
// This will return the data passed request
request = https.request({ hostname: "httpbin.org", path: "/anything", method: "GET", headers:
{ 'Content-Length': data.length, 'Content-Type': 'application/json' }}, (res) => {
console.log('/anything', res.statusCode);
res.on('data', (d) => {
console.log('/anything response: ', d.toString());
});
});
request.write(data);
request.on('error', (e) => {
console.log(`problem with request: ${e.message}`);
});
request.end();

Put Request to Firebase with NodeJS

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.]

Mavenlink API with node

I am trying to connect to mavenlink using node, but i keep getting an oauth2 validation error. Every solution online pertains to token generation for many users, but i just need to manipulate the data for use in an internal app. Does anyone have an example of oauth2 authentication for one user?
oauth2 authentication in this case is achieved with "Authorization": "Bearer key".toString('base64') inside of the headers option.
var https = require("https");
function printError (error) {
console.error(error);
}
key = 'oauth2 token';
var options = {
host: 'api.mavenlink.com',
path: '/api/v1/workspaces.json',
method: 'GET',
headers: {
"Content-type": "application/json",
"Authorization": "Bearer key".toString('base64')
}
};
var body = "";
var req = https.request(options, (res) => {
console.log('statusCode: ', res.statusCode);
console.log('headers: ', res.headers);
res.on('data', (d) => {
process.stdout.write(d);
});
res.on('data', function (chunks){
body += chunks;
});
res.on('end', function() {
if(res.statusCode == 200) {
try
{
//parse data
var massData = JSON.parse(body);
console.log(body);
} catch(error) {
//parse error
printError(error);
}
}
});
});

nodejs paypal pdt return 302

I'm using nodejs and express. This is my code that is run on the return from Paypal. I only get a 302 errors in response from Paypal. I saw a couple examples that use ssl:// instead of https:// but nodejs yells saying that its not a valid protocol for the https module. Does anyone have a working nodejs script for PDT and IPN?
var purchaseID = req.query.tx;
var atoken = MYAuthToken;
var postDataArray = {'cmd':'_notify-synch','tx': purchaseID, 'at': atoken}
var postData = JSON.stringify(postDataArray);
console.log(postData);
var options = {
hostname: 'www.sandbox.paypal.com',
port: 443,
path: '/cgi-bin/webscr',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': postData.length
}
};
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);
});
res.on('end', function() {
console.log('No more data in response.')
});
});
req.on('error', function(e) {
console.log('problem with request: '+e.message);
});
req.write(postData);
req.end();
});
This
You're missing Accept: */* header. Also, JSON.stringify is not application/x-www-form-urlencoded. Here is some working code for you to build based on:
var request = require('request');
var endpoint = 'www.sandbox.paypal.com';
var options = {
form: {
cmd: '_notify-synch',
tx: tx,
at: auth
},
headers: {
Accept: '*/*'
}
};
request.post('https://' + endpoint + '/cgi-bin/webscr', options, function(e, r, body) {
return console.log(body);
});
Try just posting without the JSON
var postData = "cmd=_notify-synch,at=" + at + ",tx=" + tx;
I've edited a couple of times as i ran into issues. I'm new to node so just hacking out a solution with trial and error. Your post moved me towards the solution. So here is postData that works with your code. It's nice to see the FAIL ans SUCCESS messages come through. Note .. need the &'s
var postData = "cmd=_notify-synch&at=" + at + "&tx=" + tx;

Resources