节点JS。发送包含XML数据的帖子

时间:2015-04-17 17:32:50

标签: xml node.js post request

我正在尝试使用一些原始XML数据发送帖子请求。然而,它不起作用。下面的代码没有发送正文,就好像我没有发送数据一样。 任何人都有任何线索如何实现这一目标?尝试了不同的模块,似乎没有人能够发送原始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

1 个答案:

答案 0 :(得分:3)

这是一个有效的例子。

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

标题取决于您使用的网络服务。此外,如果webservice提供wsdl,那将是一个巨大的缓解。