Last active
September 21, 2021 17:00
-
-
Save aurbano/3d8829c5cdb243f3fded to your computer and use it in GitHub Desktop.
Nodejs + Express : Simple proxy
This file contains hidden or 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
/** | |
* Simple image proxy for Nodejs | |
* @param {Express} app Express app | |
* @return {function} | |
*/ | |
var http = require('http'), | |
url = require('url'); | |
module.exports = function (app) { | |
app.get('/proxy/:image', function (request_from_client, response_to_client) { | |
var image_url = decodeURIComponent(request_from_client.params.image), | |
image = url.parse(image_url); | |
var options = { | |
hostname: image.host, | |
port: image.port || 80, | |
path: image.path, | |
method: 'GET' | |
}; | |
var image_get_request = http.get(options, function (proxy_response) { | |
proxy_response.headers = request_from_client.headers; | |
proxy_response.pipe(response_to_client); | |
}); | |
image_get_request.end(); | |
}); | |
} |
This file contains hidden or 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
/** | |
* Test the Proxy server running, requires the server to be running locally for the tests | |
*/ | |
var should = require('should'), | |
request = require('supertest'); | |
describe('Proxy server', function () { | |
describe('Get version', function () { | |
it('should return an image', function (done) { | |
var port = process.env.PORT || 5000; | |
request('http://localhost:' + port) | |
.get('/proxy/https%3A%2F%2Fwww.google.com%2Fimages%2Fsrpr%2Flogo11w.png') | |
.expect(200) | |
.expect('Content-Type', 'image/png') | |
.end(function (err, res) { | |
done() | |
}) | |
}); | |
}); | |
}); |
This file contains hidden or 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 express = require('express'), | |
app = express(); | |
module.exports = function () { | |
var port = process.env.PORT || 5000; | |
var server = app.listen(port, function () { | |
console.log('Proxy server started on %d', server.address().port); | |
}); | |
require('./expressProxy.js')(app); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey @jasonMisaq, I assume you are referring to the old one on my blog, but read the disclaimer there before using.