node.js - Posting xml to a url in nodejs -
i developing client program hit post url , response below code
var http = require('http'); var fs = require('fs'); var postdata = "<?xml version = '1.0' encoding = 'utf-8'?><rest><contact>aa</contact></rest>"; fs.readfile('sampledata.xml', 'utf8', function (err, filedata) { if (err) { return console.log(err); } else { console.log("\n data : \n\n" +filedata); var options = { host: 'kkk', port: 1, path: '/root', method: 'post', headers: { "content-type" : 'application/xml' } }; var reqclient = http.request(options, function(res) { res.setencoding('utf8'); res.on('data', function (chunk) { //console.log('body: ' + chunk); }); }); //posts data server reqclient.write(postdata); reqclient.end(); reqclient.on('response', function (response) { response.on('data', function (chunk) { //console.log(response.statuscode + "\n"); //console.log(response.headers); console.log("\n" + 'response: ' + chunk); }); }); } });
i tried reading xml data file plus passed data directly in req.write.both times throwing me error because xml passing string.i need solution convert string xml before passing.i stuck here.any helpful.
i tried new approach please find below code
var http = require('http'); var body='<?xml version="1.0" encoding="utf-8"?>'+ '<rest><listofln_interface>'+ '<contact>123304</contact>'+ '</listofln_interface></rest>'; var postrequest = { host: "hhhh", path: "/contact", port: 01, method: "post", headers: { 'content-type': 'application/xml', 'content-length': buffer.bytelength(body) } }; var buffer = ""; var req = http.request( postrequest , function( res ) { console.log( res.statuscode ); console.log( res.headers); var buffer = ""; var chunks = []; res.on('data', function (data) { chunks.push(data); }); res.on('end', function(){ var body1 = buffer.concat(chunks).tostring(); //var xmldoc = libxmljs.parsexml(body); // var status = xmldoc.get('//status').text(); //var ticket = xmldoc.get('//incident_id').text(); console.log(body1); }); //res.on( "data", function( data ) { buffer = buffer + data; } ); // res.on( "end", function( data ) { console.log( buffer ); } ); }); req.write( body ); req.end();
this threw me 500 internal server error.dont know goin wrong.
Comments
Post a Comment