This is an example of a proxy to keep the API authentication token safe. Instead of hardcoding the authentication token client side (on the HTML page), the token is kept server side. All requests from your App to the EValue API, instead go via your proxy. The proxy will add the authentication token to the header, and then send the request to the EValue API server.
This code snippet takes 2 arguments, methodData
and methodOptions
. methodData
contains the data sent so the API, methodOptions
contains the URL of the specific API to call and the method type (GET or POST). Here is an example of the URL to this proxy for the State Benefit Age API call: /?methodData={"dateOfBirth":"1980-05-11","gender":"FEMALE"}&methodOptions={"pathname":"/state-benefit/1.0.0/stateBenefitAge/age", "method": "POST"}
'use strict';
const request = require("request");
var token = "RWlzRDNRNG5UNUFXaHhuSkpFSTRhMktlQzdjYTpZWUVKajJtUlF3MmxyeHV2NVo0dXNlbEd5MGth";
var express = require('express');
var router = express.Router();
var apiRequest = {};
router.get('/', function getResponse(req, res, next) {
"use strict";
var methodOptions = (req.query.methodOptions) ? JSON.parse(req.query.methodOptions) : {};
var options = {
method: (typeof methodOptions.method === "string") ? methodOptions.method.toUpperCase() : 'POST',
pathname: methodOptions.pathname
};
if(typeof methodOptions.pathname !== "string"){
console.error("Error calling API. No name provided. Which API to call?");
}
var data = JSON.parse(req.query.methodData);
apiRequest.sendRequest(options, data, function (data){
console.log("sending response back to client. Response is ");
console.dir(data);
res.json(data);
});
});
router.post('/', function postResponse(req, res, next) {
res.json({'oops': 'Sorry POST response not implemented yet'});
});
/** Call the API.
* @params params Parameters for API (options, name of method to call) plus any Request options (GET/POST)
* @params body
* @params callback
*/
apiRequest.sendRequest = function sendRequest(params, body, callback) {
"use strict";
var options = apiRequest.setUpOptions(params, body);
request(options, function (error, response, responseBody) {
if (error){
console.error("Error with API call. Status code = " + response.statusCode, error);
console.dir(response.responseBody);
throw new Error(error);
}
if(typeof callback ==="function") {
callback(responseBody);
}
});
}
apiRequest.setUpOptions = function setUpOptions(params, body) {
let options = {
url : 'https://api.evalueproduction.com' + params.pathname,
method: params.method || 'POST',
headers: apiRequest.setUpHeaders(),
body : body
};
if(options.headers['Content-Type'] == "application/json") {
options.json = true;
}
return options;
}
apiRequest.setUpHeaders = function setUpHeaders() {
const headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + token,
'Cache-Control': 'no-cache'
};
return headers;
}
module.exports = router;