Created
November 4, 2016 17:27
-
-
Save dtiemann83/8d2feeddc12c5c71986d3851b6e64648 to your computer and use it in GitHub Desktop.
A quick bit of Node.JS/Express code to proxy a request to an API from a local URL, avoiding XSS and allowing safe injection of authentication params. Example includes HTTP Basic Authentication strategy. Requires 'request', 'underscore', and 'express'.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var request = require('request'), router = require('express').Router(), | |
url = require('url'), _ = require('underscore') | |
var config = { | |
api : { | |
url : { | |
protocol : "http", | |
hostname : "rest.myapi.com", | |
port : "8080" | |
}, | |
auth : "authorization-token" //Comment this out to avoid Auth headers. | |
} | |
} | |
var getAPIUrl = function(){ | |
var urlobj = config.api.url | |
var nurl = url.format(urlobj) | |
return nurl | |
} | |
router.all('/*', function(req, res, next) { | |
var purl = getAPIUrl() + req.url; | |
if(config.api.auth) | |
req.headers['authorization'] = config.api.auth | |
var mtd = req.method.toLowerCase() != "delete" ? req.method.toLowerCase() : "del" | |
var rdata = { url : purl, form : req.body } | |
var r = mtd == "get" ? request(rdata) : request[mtd](rdata) | |
req.pipe(r, { end : mtd == "get" ? true : false }).pipe(res) | |
}); | |
module.exports = router; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment