Convert XML to JSON using an Express.js proxy pipeline

In order to access an external API that does not support CORS for my front-end (angular) application, I have implemented a simple proxy using Node.JS / Express.JS to handle the requests. This setup allows me to securely store my api credentials at the proxy level, preventing any potential misuse by users on the front end.

Everything is functioning flawlessly as intended.

Check out the code snippet below:

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 I am interacting with only provides XML responses. To convert these responses into JSON on the client side, I utilize xml2js library within my front-end application.

Although this setup works efficiently, I am considering offloading the XML to JSON conversion process from the client to the server to improve performance.

I believe creating something like the following structure would streamline this process:

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

However, implementing this functionality is uncharted territory for me.

In essence, my goal is to construct an XML to JSON proxy layer on top of an existing API service.

Despite numerous resources available on Stack Overflow covering topics like "creating a proxy" and "XML to JSON conversion", I have yet to find a comprehensive guide that combines both aspects seamlessly.

Answer №1

To convert XML to JSON, you should utilize a transform stream along with a library like xml2json.

Here's a simplified example of how you can use it (this code snippet should also work with requests):

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The ajax function is malfunctioning when called from an external JavaScript file

I am having an issue with a Registration page that only has UserName and Password fields. When I click on the Submit button, I want to be able to submit the new User Details using an ajax call with jQuery. I have tried defining an Insert function on butt ...

Automatically injecting dependencies in Aurelia using Typescript

Recently, I started working with Typescript and Aurelia framework. Currently, I am facing an issue while trying to implement the @autoinject decorator in a VS2015 ASP.NET MVC 6 project. Below is the code snippet I am using: import {autoinject} from "aure ...

Using TypeScript and Node.js with Express; I encountered an issue where it was not possible to set a class property of a controller using

I have a Node application using Express that incorporates TypeScript with Babel. Recently, I attempted to create a UserController which includes a private property called _user: User and initialize it within the class constructor. However, every time I ru ...

Protractor tests are successful when run locally, but encounter failures when executed on Travis-CI

I recently integrated end-to-end tests using Protractor into my AngularJS application. Testing them locally showed that they all pass, but upon committing to GitHub and Travis for CI, most of the tests fail. The failing tests seem to be those requiring na ...

Ajax long-polling - Timeout triggering unexpectedly

I am having an issue with my Ajax code polling my IIS/ASP server. After calling msgPoll("") once, the function seems to be invoked repeatedly instead of every 30 seconds. Can you help me identify what mistake I might be making? var msgTimOut; f ...

Which option would be more beneficial for crafting a responsive UI: integrating a UI framework with three.js or solely relying on vanilla

In my quest to create a 3D editor using three.js, I find myself in uncharted territory. While I have a good grasp of JavaScript and three.js, my knowledge of web development and UI frameworks is lacking. Mrdoob's editor utilizes plain JavaScript for U ...

Input values in Angular are not being updated according to the corresponding model values

My Angular application features two routes that share the same controller and partials. Despite the shared code, the controller and partials behave slightly differently depending on the route being used. Here are the routes: $routeProvider.when('/joi ...

What is the url of the file at input.files[i]?

I've encountered an issue with my JavaScript code. Currently, when a user uploads a file, the code grabs the file name. However, I need it to fetch the file's URL on the user's PC instead. How can I implement this? This is my code snippet: ...

Combining the power of ExpressJS with a dynamic blend of ejs and React for an

My current setup involves a NodeJS application with an Express backend and EJS for the frontend. The code snippet below shows an example route: router.get("/:name&:term", function(req, res) { Course.find({ courseName: req.params.name, courseTerm: req.p ...

Utilizing the Twitter API with Next.js to automate tweets even when the website is not actively engaged

Currently, I am utilizing next.js for the development of a web application. My goal is to have this app automatically post to my Twitter account. I have already set up a developer account on Twitter and an API in nextjs. By calling the API, it will trigger ...

Managing JavaScript with Scrapy

Spider for reference: import scrapy from scrapy.spiders import Spider from scrapy.selector import Selector from script.items import ScriptItem class RunSpider(scrapy.Spider): name = "run" allowed_domains = ["stopitrightnow.com"] start_urls = ...

TypeScript struggling to recognize specified types when using a type that encompasses various types

I have a defined type structure that looks like this: export type MediaProps = ImageMediaProps | OembedProps; Following that, the types it references are defined as shown below: type SharedMediaProps = { /** Type of media */ type: "image" | "oembed"; ...

Tips for transferring a variable to another .php file using ajax

Is there a way to pass the id in posts.php using ajax while keeping the href value as "#"? Currently, when I click on this link, it redirects to that link. However, I do not want to navigate to the link and still need to pass the id in posts.php. Any sug ...

What might be causing AngularJS to fail to display values when using TypeScript?

I have designed the layout for my introduction page in a file called introduction.html. <div ng-controller="IntroductionCtrl"> <h1>{{hello}}</h1> <h2>{{title}}</h2> </div> The controller responsible for handling th ...

The Kendo Date Picker is failing to update properly when the k-ng-model is modified

I am facing an issue with my code involving two date pickers and one dropdown list. I want the date pickers to change based on the selected item from the dropdown list. Here is the relevant portion of my code: $scope.toolbarOptions = { i ...

Direct the /username path to /[user]/[tab].js instead of [user]/index.js in Next.js

My goal is to develop a user profile page that displays content based on the current tab the user is viewing. The tab is determined by what is provided in the URL (e.g. /username/tab1). The challenge I am facing is that one of the tabs the user can access ...

What is the best way to manage the changing selection in a drop-down list?

Can someone help me with a coding issue I am facing? <select name="txtTK" > <option value="None">---</option> <option value="Mat">Materials</option> <option value="Cate">Category</option> <option ...

Sending an object from Rails to Javascript

My MapsController is def show @outlet=OUtlet.all render 'maps/map' end In the view page map.html.erb, I iterate through each outlet to display their latitude and longitude: <% @outlet.each do |product| %> <%= product.latitu ...

Transferring data from PHP to JavaScript using AJAX

I'm currently working on a project that involves generating random numbers on both JavaScript and PHP pages, and I need to display them on the HTML page using JavaScript. So far, I have successfully set up both pages to generate random numbers. Howev ...

Retrieve the file name (as well as other properties) when clicking on an image in dropzone.js

Is there a way in dropzone.js to retrieve the file name of an uploaded image when it is clicked? Check out this resource for more information: ...