I am trying to create a web application that has to make a REST call to a CDAP Server. When I tried using the typical jQuery/AJAX I was running into CORS/Access-Control-Allow-Origin issue due to the obvious reason that this would be a cross domain request. Sadly, CDAP does not support CORS.
Now the only option I am left out with is to create a Server Side proxy. The following is the setup:
- Nodejs exposes a generic end point (/rest/*) for all calls from the browser.
- Browser making all calls to the node proxy for cdap resources.
The following is the flow of control between browser, Nodejs proxy & CDAP,
- Browser
- Makes (http) calls to the node proxy.
- Nodejs server
- Receives the http calls from browser and changes the url appropriately to make the same request to CDAP backend.
- Gets a response from CDAP for the above request and routes it back to the client.
Nodejs proxy is running at localhost:8500
CDAP instance is running at localhost:10000
Browser:
- Create a new app in JS (with url being - http://localhost:8500/rest/v3/namespaces/default/apps/S3Text)
Nodejs proxy:
- Receives this request and modifies the url to - http://localhost:10000/v3/namespaces/default/apps/S3Text and makes a request to CDAP backend.
- Once it receives a response from the cdap backend, it then re-routes the response to the client.
The curl equivalent of this REST call is below:
curl -v localhost:10000/v3/namespaces/default/apps/S3Text -H "Content-Type: application/json" -d @new.json -X PUT
I am new to Node.js but have read some documentation and went through few videos. The point where I am stuck is which part I need to load the JSON file and other parameters like method, data, dataType, etc. Will it be in the JS code or in the Node.js proxy server code. If it has to go in the nodeProxy.js code, then where and how do I need to pass them? My apologies if I am being naive.
JS Code:
function sendCurlRequest(){
var jsonData = <JSON_DATA>;
$.ajax({
cache : false,
method: "PUT",
crossDomain: true,
url: 'http://localhost:8500/rest/v3/namespaces/default/apps/S3Text',
data: jsonData,
dataType: "json",
contentType: "application/json",
success: function(data){
alert("Success");
},
error: function(data){
alert("Error: " + JSON.stringify(data));
},
complete: function(data){
console.log("Call Completed");
}
});
}
nodeProxy.js code:
var http = require('http');
var httpRequest = require('request');
var destinationURL = 'http://localhost:1000/v3/namespaces/default/apps/S3Text';
http.createServer(function (req, res) {
var options = {
url: destinationURL
}
var destinationResponse = req.pipe(request(options))destinationResponse.pipe(res)
}).listen(8500, 'localhost');
console.log('Server running at http://localhost:8500');
If you're willing to use some Node modules then this may work though I don't think it will change your URL from
localhost:8500/rest/v3
tolocalhost:10000/v3
. The/rest/
will stay in.JS
Node