Skip to content

Instantly share code, notes, and snippets.

@JhonatanHern
Created September 13, 2018 15:03
Show Gist options
  • Save JhonatanHern/891214199519c87b20277847f21b54ff to your computer and use it in GitHub Desktop.
Save JhonatanHern/891214199519c87b20277847f21b54ff to your computer and use it in GitHub Desktop.
lightweight proxy made in node.js to avoid cors issues when working with holochain and React.js. Became useless with the usage of the "proxy" option in the "dna.json" file. Preserved for educational purposes since it handles several important concepts for begginers.
const http = require('http'),
url = require('url')
const PORT = 3939
const allowedSources = [
'::1',
'localhost',
/^127\.0\.0\.\d\d?\d?$/
]
function isAllowed(address) {
for (var i = allowedSources.length - 1; i >= 0; i--) {
let a = allowedSources[i]
if( (typeof a === 'string' && a === address) || (a instanceof RegExp && a.test(address)) ) {
return true
}
}
return false
}
function postData(data,path) {
return new Promise((succ,error) => {
const postheaders = {
'Content-Type' : 'application/json',
'Content-Length' : Buffer.byteLength(data)
}
const optionspost = {
host : 'localhost',
port : 4141,
path : path,
method : 'POST',
headers : postheaders
}
let result = ''
let reqPost = http.request(optionspost, function(res) {
res.on('data' , function( d ) { result += d })
res.on('end' , function( ) { succ(result) })
})
// write the json data
reqPost.write(data)
reqPost.end()
reqPost.on('error', function(e) {
error(e)
})
})
}
const server = http.createServer(async (req, res) => {
if (!isAllowed(res.socket.remoteAddress)) {
res.writeHead(400, {
'Content-Length': 16,
'Content-Type': 'text/plain'
})
res.end('400. Bad Request')
return
}
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000')
let params = url.parse(req.url,true).query
if (!params.path) {
res.end('')
return
}
const body = await postData( params.data , params.path )
const content_length = body.length
res.writeHead(200, {
'Content-Length': content_length,
'Content-Type': 'text/plain'
})
res.end(body)
})
function successServer() {
console.log('Server is running on port 3939')
}
server.listen(PORT,successServer)
server.on('error', (e) => {
if (e.code === 'EADDRINUSE') {
console.log('Address in use, retrying...')
setTimeout(() => {
server.close()
server.listen(PORT,successServer)
}, 1000)
}else{
console.log('unknown error ' + e.code)
console.log('Quitting...')
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment