I am trying to do the following on a high level, using node (express, https modules):
listen for POST requests (say R1) on /example endpoint (express app)
read the post payload from the request, process it repackage it and make an https POST request (say R11) to an external REST API.
read the post payload from the response to R11, process it repackage it and send as a response to R1.
Problem is, how to send response from within callbackExternalApi ? Please see code below and question in comments.
const callbackExternalApi =
function (response) {
response.on('data',
function(data) {
// do some processing on data
var processedData = ...
**// I want response_R1 over here
// so that I can do the following
response_R1.send(processedData)
// how do I get response_R1 over here??**
})
}
const requestHandlerExample =
function (request_R1, response_R1) {
// payload
var postBodyJson = '' // some payload here
// headers
var postHeaders = {
'content-type' : 'application/json',
'accept' : 'application/json'
}
// options
var postOptions = {
'host' : 'localhost',
'port' : '9000',
'path' : '/external/rest/api',
'method' : 'POST',
'headers' : postHeaders
}
// do the post call
var postRequest = _httpsModule.request(postOptions, callbackExternalApi)
postRequest.write(postBodyJson);
postRequest.end();
postRequest.on('error', function(error) {
console.error('an error occured'+error)
})
}
_app.post('/example', requestHandlerExample)
Thanks,
Jatin
I just defined global variables for response_R1 and set those in the requestHandlerExample callback. Not sure if that's the best approach, but it works.
var _response_R1
const callbackExternalApi =
function (response) {
response.on('data',
function(data) {
// do some processing on data
var processedData = ...
_response_R1.send(processedData)
})
}
const requestHandlerExample =
function (request, response) {
_response_R1 = response // set this for use in callbackExternalApi
// payload
var postBodyJson = '' // some payload here
// headers
var postHeaders = {
'content-type' : 'application/json',
'accept' : 'application/json'
}
// options
var postOptions = {
'host' : 'localhost',
'port' : '9000',
'path' : '/external/rest/api',
'method' : 'POST',
'headers' : postHeaders
}
// do the post call
var postRequest = _httpsModule.request(postOptions, callbackExternalApi)
postRequest.write(postBodyJson);
postRequest.end();
postRequest.on('error', function(error) {
console.error('an error occured'+error)
})
}
_app.post('/example', requestHandlerExample)
Related
I've tried SOAP SSL with different module, and it's working like a charm (code is here)
// var request = require('request');
// var auth = "Basic " + new Buffer("user" + ":" + "pwd").toString("base64")
// var options = {
// 'method': 'GET',
// 'url': 'https://put_correct_soap_url?wsdl',
// 'headers': {
// 'Authorization': auth
// }
// };
// process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = '0';
// request(options, function (error, response) {
// if (error) throw new Error(error);
// console.log(response.body);
// });
here comes my original requirement to manage the connectivity using existing code (module name is soap).
create client is working with older wsdl but it isn't working with the recently upgraded version of wsdl, it always returns the error "ECONNREFUSED IP:80". I've tried with multiple scenarios like wsdl_headers, wsdl_options, blank etc ... still no luck ... any help would highly be appreciated ... thanks!
// var auth = "Basic " + new Buffer("user" + ":" + "pwd").toString("base64")
/wsdl'
//reqeust : req
// forceSoap12Headers: true,
// rejectUnauthorized: false,
// strictSSL: false,
// wsdl_headers: {
// 'Authorization': auth ,
// Connection : 'keep-alive'
// }
// ,
// wsdl_options : {
// gzip : true,
// secureProtocol : 'TLSv1_2_method'
// }
};
process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = '0';
soap.createClient( url_new
, options
, function(err, client) {
console.log(err)
client.describe();
});
Error: connect ECONNREFUSED [IP]:80\n at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1145:16)\n at TCPConnectWrap.callbackTrampoline (internal/async_hooks.js:126:14
I am using Paytm payment gateway for transaction. My front-end is in reactjs and backend is in nodejs and expressjs. I wanted that after successful payment next page is redirected.
Backend Code-
for checking checksum and transaction.
PaytmChecksum.generateSignature(JSON.stringify(paytmParams.body), paytmconfig.merchantkey).then(function(checksum){
paytmParams.head = {
"signature" : checksum
};
var post_data = JSON.stringify(paytmParams);
var options = {
/* for Staging */
hostname: 'securegw-stage.paytm.in',
/* for Production */
// hostname: 'securegw.paytm.in',
port: 443,
path: '/v3/order/status',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': post_data.length
}
};
// Set up the request
var response = "";
var post_req = https.request(options, function(post_res) {
post_res.on('data', function (chunk) {
response += chunk;
});
post_res.on('end', function(){
console.log('Response: ', response);
res.write(response)
});
});
// post the data
post_req.write(post_data);
post_req.end();
});
Front-end code:
will call onPayment function for making the payments
onPayment= async(e)=>{
e.preventDefault();
try {
var amount="1.00";
var mobile_number="+919999999999";
var email="abcd#gmail.com";
var orderId="ORDER_ID"+(new Date().getTime());
let params={
orderId:orderId,
email:email,
amount:amount,
mobile_number:mobile_number
}
var url="http://localhost:4000/payment/paynow";
var request={
url:url,
params:params,
method:"get"
}
const response = await Axios(request);
const processParams=await response.data;
console.log(processParams);
var details={
action : "https://securegw-stage.paytm.in/order/process",
// params : params
params : processParams
}
this.post(details);
} catch (error) {
}
}
You can use react-router-dom
import {useHistory} from 'react-router-dom'
const history = useHistory()
history.push('yourNextPage', {details:detail})
either history.replace should work:
history.replace('yourNextPage', {details:detail})
EDIT
{details:detail} is in case you want to pass your next page a state from the previous page
if you dont want to pass any state
it would be enough
history.push('yourNextPage')
Please refer the code available on the below repository for checksum in node.js.
https://github.com/paytm/Paytm_Node_Checksum
You can also refer the below repository for react (front-end)
https://github.com/paytm/paytm-blink-checkout-react
I'm making a HTTP request to a password protected site using the request module in npm, putting in a password, storing a cookie, then making the request once the cookie is stored and verified. I am able to get the same headers as I would on a normal browser request, but hte body itself, instead of being the HTML document I get in a browser, just looks like this:
� �Z�r�H��c��䞙��pT���Ī$3�ƾ�~Y�#�MK8���>*��?�z)�?U���ݨ�J�혳��섯tB��x��c��?�����������0�H�����V��O'�7����}���L�"˖}/ta�xn�g#�ݱ�O�����
Any ideas what might be causing this or how I can fix it?
In addition, when I run this from the command prompt, the computer "dings"
Here is the full node.js code I am running (minus the URLs/passwords/etc.)
var parsedurl1 = url.parse( urlstring1 );
var options1 = {
hostname: parsedurl1.hostname,
port: ( parsedurl1.port || 80 ), // 80 by default
method: 'POST',
path: parsedurl1.path,
headers: {
'Host': hostname
,'User-Agent': myuseragent
,'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'
,'Accept-Language':"en-US,en;q=0.5"
,'Accept-Encoding': "gzip, deflate"
,'Referer': hostname
,'Content-Type': "text/html; charset=utf-8"
,'Content-Length': Buffer.byteLength(postData)
,'Connection': "keep-alive"
,'Upgrade-Insecure-Requests': "1"},
};
var cookiefile ;
var postData=querystring.stringify({
'email': myemail
,'password':mypassword
,'action': 'login'
,'go.x': 0
,'go.y': 0
})
var cookiefile;
var callback = function ( response ) {
// display returned cookies in header
var setcookie = response.headers["set-cookie"];
if ( setcookie ) {
setcookie.forEach(
function ( cookiestr ) {
cookiefile = cookiestr;
fs.writeFile(cookiefilelocation, cookiestr);
console.log( "COOKIE:" + cookiestr );
}
);
}
var data = "";
response.on(
"data",
function ( chunk ) { data += chunk; }
);
response.on(
"end",
function () {
newcookiefile = cookiefile.substr(0, cookiefile.indexOf(";"));
var parsedurl2 = url.parse( urlstring2 );
var options2 = {
url: urlstring2,
// port: ( parsedurl2.port || 80 ), // 80 by default
method: 'GET',
// path: parsedurl2.path,
headers: {
"Host": hostname
,"User-Agent": myuseragent
,'Accept': "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
,'Accept-Language':"en-US,en;q=0.5"
,'Accept-Encoding': "gzip, deflate"
,'Referer':hostname
,'Cookie': newcookiefile
,'Connection': "keep-alive"
,'Upgrade-Insecure-Requests': "1"},
};
function callback3(error, response, body){
console.log('error:', error); // Print the error if one occurred
console.log('statusCode:', response.headers ); // Print the response status code if a response was received
console.log('body:', body.substr(1,1000));
fs.writeFile('./config/pullfiles/mostrecent.txt', body);
}
requestlib(options2, callback3);
}
);
};
var request = http.request(options1, callback);
request.on(
"error",
function( err ) {
console.error( "RERROR:" + err );
}
);
request.write(postData);
request.end(); // let request know it is finished sending
I figured it out! This gibberish was caused by my lack of the 'gzip: true' option is my request(). Now the second request reads:
url: urlstring2
,gzip: true
,headers:{...
I am using npm request module (https://www.npmjs.com/package/request) to post binary content to a servlet. The binary content is received as part of http request, using the npm request module it is then posted to the J2ee server.
Along with the post, I need to pass some custom headers. I am using the below code to do that
var req = require('request');
function upload(request, response) {
var options = {
headers: {
'customheader1': 'val1',
'customheader2': 'val2'
}
};
var target = req.post('http://'+host+':'+port+'/myapp/Upload', options);
request.pipe(target);
target.on('finish', function() {
console.log('Uploaded with headers');
})
}
However, the headers are going as blank to the server. What would be the right way to pass headers using request.post?
As per request Docs (http://github.com/request/request)
var req = require('request');
function upload(request, response) {
var options = {
url: 'http://'+host+':'+port+'/myapp/Upload',
headers: {
'customheader1': 'val1',
'customheader2': 'val2'
}
};
var target = req.post( options, function(err,data){
console.log('uploaded with headers')
})
request.pipe(target);
}
I'm unable to get the var data I sent in via a POST method. This should be easy (right?), but I'm clearly missing something (either conceptually or a setting).
At this stage, I simply want to check to see if the server side code will output the data to the console. The array is being stringify-ed correctly, eg. ['one','two','three'] becomes 0=one&1=two&2=three
but I can't pull it out on the server side.
What am I missing?
Client side
var qs = require('querystring')
, http = require('http');
var some_array = ['one','two','three'];
var data = qs.stringify(some_array);
var options = { host: 'localhost',
path: '/search',
port: '3000',
method: 'POST',
headers: { 'content-length': Buffer.byteLength(data),
'Content-Type': 'application/json' }
}
function go_post(data) {
req = http.request(options, function(res) {
// do something with response
});
req.write(data);
req.end();
};
go_post(data);
Server side
var connect = require('connect');
var qs = require('querystring');
var server = connect.createServer();
server.use(function(req,res,next) {
if ( '/search' == req.url && req.method == 'POST' ) {
// quick check to see if data came through
console.log('BODY IS ' + req.data);
} else {
next();
};
});
These objects arent available because they are still in the "raw" request. You have to use a middleware like connect().use(connect.bodyParser()) in order to get them from the request via req.data.