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.
Related
I am learning node, but can't figure out how to send a POST request with a string.
Here is my code:
const h = require('https');
h.post("https://VLang.johnstev111.repl.co", "print('test')")
This should do pretty much what you wish, we log the response and any errors.
I've set the content-type to 'text/plain', and you can change the data by setting the postData variable to whatever you wish.
const https = require('https');
// Put your post data here
const postData = "print(40 + 2)";
const options = {
hostname: 'VLang.johnstev111.repl.co',
method: 'POST',
headers: {
'Content-Length': postData.length
}
};
const req = https.request(options, (res) => {
console.log('Response: status:', res.statusCode);
console.log('Response: headers:', res.headers);
res.on('data', (d) => {
process.stdout.write("Response: " + d);
});
});
req.on('error', (e) => {
console.error("An error occurred:", e);
});
req.write(postData);
req.end();
I am getting truncated response in my node service.
I am using http request.Please notify me any error in this code.
I want to get response without losing data.
My Code :
var config = require('./configuration')
exports.postDataDetails = function postDataDetails(http,url,port,path,inputParam,callback){
var postData = inputParam;
var options = {
hostname: url+":",
port: port,
path: path,
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Basic ' + new Buffer(config.headerUsername + ':' + config.headerPassword).toString('base64'),
'Content-Length': Buffer.byteLength(postData,'utf8')//postData.length
}
};
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);
return callback(chunk);
});
res.on('end', function() {
console.log('No more data in response.');
return callback(JSON.stringify({status : "No more data in response."}));
})
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
return callback(JSON.stringify({status : "error"}));
});
// write data to request body
req.write(postData);
req.end();
}
How to fix that problem.
Thanks.
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;
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);
}
I have a piece of code that's supposed to do a http get request. The program exited successfully without error, but I didn't see any response and it didn't even go inside the callback function! At first I thought it's because http is asynchronous and put a large loop in the end but that didn't work either. Does anyone know this issue? Only the first console log sendHttpRequest and 444 gets printed. I also tried the http.get but it didn't work either.
function sendHttpRequest (url, callBack) {
console.log("sendHttpRequest");
//constrct options
var options = {
host: 'www.google.com',
path: '/index.html',
method: 'GET',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
};
http.get("http://www.google.com/index.html", function(res) {
console.log("Got response: " + res.statusCode);
});
var req = http.request(options, function(res) {
console.log("333");
var output = '';
console.log(options.host + ':' + res.statusCode);
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log("DATATATAT!")
output += chunk;
});
res.on('end', function () {
console.log('222');
var obj = JSON.parse(output);
callBack(res.statusCode, obj);
});
});
req.on('error', function (err) {
console.log('error: ' + err.message);
});
req.end();
console.log("444");
}
}
Update
The grunt task terminated before the OP received a response; adding async and a callback to the task fixed it.
If I take your code outside of the function and prepend var http = require('http'); I get a response up until 222, at which point it dies with SyntaxError: Unexpected token <. Which is actually dying because you're trying to parse an HTML response as JSON.
If you paste the entire script below and run it end to end, the console dies with:
undefined:1
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
^
SyntaxError: Unexpected token <
at Object.parse (native)
at IncomingMessage.<anonymous> (/Users/you/nodetest/tmp/test.js:31:28)
at IncomingMessage.EventEmitter.emit (events.js:120:20)
at _stream_readable.js:896:16
at process._tickCallback (node.js:599:11)
The script:
var http = require('http');
console.log("sendHttpRequest");
//constrct options
var options = {
host: 'www.google.com',
path: '/index.html',
method: 'GET',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
};
http.get("http://www.google.com/index.html", function(res) {
console.log("Got response: " + res.statusCode);
});
var req = http.request(options, function(res) {
console.log("333");
var output = '';
console.log(options.host + ':' + res.statusCode);
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log("DATATATAT!")
output += chunk;
});
res.on('end', function () {
console.log('222');
// it's failing on the next line, because the output
// it's receiving from Google is HTML, not JSON.
// If you comment out this line and simply
// "console.log(output)" you'll see the HTML response.
var obj = JSON.parse(output);
callBack(res.statusCode, obj);
});
});
req.on('error', function (err) {
console.log('error: ' + err.message);
});
req.end();
console.log("444");