Created
May 22, 2020 03:38
-
-
Save syuji-higa/f1ddacadb2744d29bb840fe16077b77e to your computer and use it in GitHub Desktop.
Node.js - proxy server
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
const internalIp = require('internal-ip') | |
const express = require('express') | |
const proxy = require('express-http-proxy') | |
const app = express() | |
require('colors') | |
const isLocalIpHosting = process.argv[2] === 'local-ip-hosting' | |
;(async() => { | |
const host = '0.0.0.0' | |
const port = 8080 | |
const proxyUrl = 'http://develop.example.com/api/v1/' | |
const clientIp = isLocalIpHosting ? await internalIp.v4() : 'localhost' | |
const clientPort = 3000 | |
const clientUrl = `http://${clientIp}:${clientPort}` | |
app.use( | |
proxy(proxyUrl, { | |
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 | |
let data = null | |
try { | |
data = JSON.parse(proxyResData.toString('utf8')) | |
} catch (err) { | |
return proxyResData | |
} | |
console.log(`${'[RES]'.yellow} ${new Date().toString().gray}`) | |
console.log(`${statusCode.toString().magenta} ${statusMessage.toString().blue}`); | |
console.log(data) | |
console.log('') | |
return proxyResData | |
} | |
}) | |
) | |
app.listen(port, host, () => { | |
console.log('listening at http://%s:%s', host, port) | |
console.log('') | |
}) | |
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment