Reputation: 5041
I am trying to send a post request with some raw XML data. However it's not working. The code below sends no body, as if I send no data. Anybody has any clue how to achieve this? Tried different modules, none seemed to be able to send raw XML.
var http = require('http');
var querystring = require('querystring');
var postData = '<?xml version="1.0" encoding="utf-8" standalone="yes"?><SearchPrices><City Code="19333" /></SearchPrices>';
var options = {
hostname: 'postcatcher.in',
port: 80,
path: '/catchers/553133a9acde130300000f08',
method: 'POST',
headers: {
'Content-Type': 'application/xml',
'Content-Length': 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);
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
// write data to request body
req.write(postData);
req.end();
Ideas appreciated
EDIT: Here is a PHP code that uses this service successfully.
$xml_data ='<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<SearchPrices>
<City Code="19333" />
<PaxNationality Code="AR" />
<Language Code="ES" />
<CheckInDate><![CDATA[2015-04-21]]></CheckInDate>
<CheckOutDate><![CDATA[2015-04-23]]></CheckOutDate>
<IncludeRoomName />
<IncludeCancellationCharges />
<IncludePromoName />
<IncludeGeorefInfo />
<RoomsCriteria>
<Room Number="1">
<Adults>2</Adults>
</Room>
</RoomsCriteria>
</SearchPrices>
';
$URL = "URL";
$ch = curl_init($URL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_ENCODING , 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/html', 'Authorization: '.$encodeText, 'Accept-Encoding: deflate'));
curl_setopt($ch, CURLOPT_POSTFIELDS, "$xml_data");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
print_r($output);
enter code here
Upvotes: 2
Views: 11672
Reputation: 5041
Here's a working example.
var request = require('request');
var xml2js = require('xml2js');
var parser = new xml2js.Parser({explicitArray: false, trim: true});
function(url, xml, cb) {
var self = this;
var options = {
method: 'POST',
keepAlive: false,
url: url,
headers: {
"Authorization": "Basic " + this.auth,
'Content-Type': 'application/x-www-form-urlencoded',
'Accept-Encoding': 'gzip',
},
body: xml,
gzip: true //depending on the webservice, this has to be false
};
var x = request(options, function (error, response, body) {
//I convert the response to JSON. This is not mandatory
parser.parseString(body, function(err, result) {
cb(null, result);
});
});
};
The headers will depend on the webservice you are using. Also, if the webservice provides wsdl, that's a huge relieve.
Upvotes: 3