我正在尝试发送带有一些原始 XML 数据的 POST 请求。但是它不起作用。下面的代码不发送正文,就好像我没有发送数据一样。 有人知道如何实现这一目标吗?尝试了不同的模块,似乎没有一个能够发送原始 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();
赞赏想法
编辑: 下面是成功使用此服务的 PHP 代码。
$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
最佳答案
这是一个有效的示例。
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);
});
});
};
header 将取决于您正在使用的网络服务。另外,如果 Web 服务提供 wsdl,那就是一个巨大的缓解。
关于xml - Node JS。发送带有 XML 数据的帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29705873/