20

i am trying to submit a xml request to a web service via Node.js using http.request.

Here is my code. My issue is that instead of data=1 i want to post xml to the service.

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

Ho to do this?

Mithun Satheesh
  • 27,240
  • 14
  • 77
  • 101

3 Answers3

28

Actually the link given by Andrey Sidorov helped to get it working. This works.

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();
Community
  • 1
  • 1
Mithun Satheesh
  • 27,240
  • 14
  • 77
  • 101
9

http.request returns ClientRequest object which is also a writable stream. Instead of .end() do end(xmlbody) or .write(xmlbody).end()

Mithun Satheesh
  • 27,240
  • 14
  • 77
  • 101
Andrey Sidorov
  • 24,905
  • 4
  • 62
  • 75
1
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
    }
});
Vinodh Ram
  • 709
  • 1
  • 9
  • 22