Skip to content

Instantly share code, notes, and snippets.

@amir-rahnama
Last active November 3, 2015 14:32
Show Gist options
  • Save amir-rahnama/50c9c2706c727bb4a86e to your computer and use it in GitHub Desktop.
Save amir-rahnama/50c9c2706c727bb4a86e to your computer and use it in GitHub Desktop.
Express.js Proxy to bypass cross-origin (CORS) HTTPS requests
var express = require('express'),
app = express(),
https = require('https'),
request = require('request'),
bodyParser = require('body-parser'),
PROXY_PORT = 12345,
HTTPS_POST = 443,
API_ENDPOINT = '/api',
CONTENT_TYPE = 'application/json',
HTTPS_HOST = 'sub.domain.com',
HTTP_METHOD = 'POST';
app.listen(PROXY_PORT);
console.log('EXPRESS.JS SERVER LISTENING ON PORT:', PROXY_PORT)
app.use(bodyParser.json());
app.use(API_ENDPOINT, function(req, res, next) {
var options = {
hostname: HTTPS_HOST,
port: HTTPS_POST,
path: API_ENDPOINT + req.url,
method: HTTP_METHOD,
headers: {
'Content-Type': CONTENT_TYPE
}
},
body = '';
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
console.log(new Date(), ' -- Rquest Received:', req.body, req.url);
var requ = https.request(options, function(https_res) {
console.log(new Date(), 'statusCode: ', https_res.statusCode);
console.log(new Date(), 'headers: ', https_res.headers);
https_res.on('data', function(d) {
body += d;
});
https_res.on('end', function() {
res.send(body);
console.log(new Date(), 'Sent request: ', req.body);
next();
});
});
requ.write(JSON.stringify(req.body));
requ.end();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment