Skip to content

Instantly share code, notes, and snippets.

@syuji-higa
Last active August 4, 2020 03:01
Show Gist options
  • Select an option

  • Save syuji-higa/55c382480a27bad12c96943bbcc7952d to your computer and use it in GitHub Desktop.

Select an option

Save syuji-higa/55c382480a27bad12c96943bbcc7952d to your computer and use it in GitHub Desktop.
Node.js - reverse proxy
const internalIp = require('internal-ip')
const express = require('express')
const proxy = require('express-http-proxy')
const app = express()
const https = require('https')
const { readFileSync } = require('fs')
require('colors')
const isLocalIpHosting = process.argv[2] === 'local-ip-hosting'
const isHttps = process.argv[2] === 'https'
const server = isHttps ? https.createServer({
key: readFileSync('localhost-key.pem'),
cert: readFileSync('localhost.pem')
}, app) : app
;(async() => {
const host = '0.0.0.0'
const port = 8080
const proxyUrl = 'https://example.com/api/v1/'
const clientIp = isLocalIpHosting ? await internalIp.v4() : 'localhost'
const clientPort = 3000
const clientUrl = `http://${clientIp}:${clientPort}`
app.options('*', (req, res) => {
res.header('Access-Control-Allow-Origin', clientUrl)
res.header('Access-Control-Allow-Credentials', true)
res.header('Access-Control-Allow-Methods', 'PUT, DELETE, PATCH')
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization')
res.sendStatus(200)
})
app.use(
proxy(proxyUrl, {
limit: '15mb',
filter: (req, res) =>{
return req.method !== 'OPTIONS'
},
proxyReqBodyDecorator(bodyContent, srcReq) {
console.log(`${'[REQ]'.yellow} ${new Date().toString().gray}`)
const { method, url, query } = srcReq
console.log(`${method.magenta} ${url}`)
if (Object.keys(query).length) {
console.log(query)
}
if (bodyContent) {
try {
console.log(JSON.parse(bodyContent.toString('utf8')))
} catch (err) {
return bodyContent
}
}
console.log('')
return bodyContent
},
userResHeaderDecorator(headers, userReq, userRes, proxyReq, proxyRes) {
headers['Access-Control-Allow-Origin'] = clientUrl
headers['Access-Control-Allow-Credentials'] = true
return headers;
},
userResDecorator(proxyRes, proxyResData, userReq, userRes) {
const { statusCode, statusMessage } = proxyRes
console.log(`${'[RES]'.yellow} ${new Date().toString().gray}`)
let data = null
try {
data = JSON.parse(proxyResData.toString('utf8'))
} catch (err) {
console.log('ERROR'.red)
console.error(err);
}
console.log(`${statusCode.toString().magenta} ${statusMessage.toString().blue}`);
console.log(data)
console.log('')
return proxyResData
}
})
)
server.listen(port, host, () => {
const protocol = isHttps ? 'https' : 'http'
console.log(`listening at ${protocol}://%s:%s`, host, port)
console.log('')
})
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment