如何在node.js http.request中发布XML数据

时间:2012-12-24 07:12:48

标签: node.js post xmlhttprequest express

我正在尝试使用http.request通过Node.js向Web服务提交xml请求。

这是我的代码。我的问题是,而不是data=1我希望将xml发布到服务中。

http.request({
   host: 'service.x.yyy.x',
   port: 80,
   path: "/a.asmx?data=1",
   method: 'POST'
}, function(resp) {
   console.log(resp.statusCode);
   if(resp.statusCode) {
        resp.on('data', function (chunk) {
            console.log(chunk);
            str +=  chunk;                  
        });
        resp.on('end', function (chunk) {                           
            console.log(str);            
        });                   
  }
}).end();

何你这样做?

3 个答案:

答案 0 :(得分:22)

实际上Andrey Sidorov给出的链接有助于它的运作。 这很有效。

var body = '<?xml version="1.0" encoding="utf-8"?>' +
           '<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">'+
            '<soap12:Body>......</soap12:Body></soap12:Envelope>';

var postRequest = {
    host: "service.x.yyy.xa.asmx",
    path: "/a.asmx",
    port: 80,
    method: "POST",
    headers: {
        'Cookie': "cookie",
        'Content-Type': 'text/xml',
        'Content-Length': Buffer.byteLength(body)
    }
};

var buffer = "";

var req = http.request( postRequest, function( res )    {

   console.log( res.statusCode );
   var buffer = "";
   res.on( "data", function( data ) { buffer = buffer + data; } );
   res.on( "end", function( data ) { console.log( buffer ); } );

});

req.on('error', function(e) {
    console.log('problem with request: ' + e.message);
});

req.write( body );
req.end();

答案 1 :(得分:6)

http.request返回ClientRequest对象,该对象也是可写流。 而不是.end()执行end(xmlbody).write(xmlbody).end()

答案 2 :(得分:0)

var request = require("request");
request.post({
    rejectUnauthorized: false,
    url: 'URL',
    method: "POST",
    headers: {
        'Content-Type': 'application/xml',
    },
    body: '<XML>'
}, function (error, response, body) {
    if (error) {
        // Handle error
    } else {
        // Handle Response and body
    }
});