javascript - Express.js proxy pipe translate XML to JSON -


for front-end (angular) app, need connect external api, not support cors.

so way around have simple proxy in node.js / express.js pass requests. additional benefit can set api-credentials @ proxy level, , don't have pass them front-end user might steal/abuse them.

this working perfectly.

here's code, record:

var request = require('request'); var config = require('./config');  var url   = config.api.endpoint; var uname = config.api.uname; var pword = config.api.pword; var headers = {     "authorization" : 'basic ' + new buffer(uname + ':' + pword).tostring('base64'),     "accept" : "application/json" };  exports.get = function(req, res) {   var api_url = url+req.url;   var r = request({url: api_url, headers: headers});   req.pipe(r).pipe(res); }; 

the api-endpoint have use has xml output format. use xml2js on front-end convert xml reponse json.

this working great, lighten load client, , xml -> json parsing step on server.

i assume have create like:

req.pipe(r).pipe(<convert_xml_to_json>).pipe(res); 

but don't have idea how create that.

so i'm looking create xml json proxy layer on top of existing api.

there lot of questions on regarding "how make proxy" , "how convert xml json" couldn't find combine two.

you need use transform stream , xml json conversion need library use xml2json

..then u use (simplified should work request too)

var http = require('http'); var fs = require('fs'); var parser = require('xml2json'); var transform = require('stream').transform;   function xmlparser () {   var transform = new transform();   transform._transform = function(chunk, encoding, done) {     chunk = parser.tojson(chunk.tostring())     console.log(chunk);     this.push(chunk);     done();   };    transform.on('error', function (err) {     console.log(err);   });    return transform; }  var server = http.createserver(function (req, res) {   var stream = fs.createreadstream(__dirname + '/data.xml');   stream.pipe(xmlparser()).pipe(res); }); server.listen(8000); 

Popular posts from this blog

c# - ODP.NET Oracle.ManagedDataAccess causes ORA-12537 network session end of file -

matlab - Compression and Decompression of ECG Signal using HUFFMAN ALGORITHM -

utf 8 - split utf-8 string into bytes in python -