Created
March 10, 2019 23:47
-
-
Save chulman444/bdb53bec093d41e114bd0f1008280c79 to your computer and use it in GitHub Desktop.
Proxy with express and axios
This file contains 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 axios = require('axios') | |
const proxy = require("express-http-proxy") | |
const appFactory = () => require("express")() | |
const PORT = [ | |
[3010, factoryFirst], | |
[3011, factorySecond], | |
[3012, factoryThird] | |
] | |
for(let [port, factory] of PORT) { | |
let app = appFactory() | |
factory(app, port) | |
} | |
function runServer(app, port) { | |
app.listen(port, () => { | |
console.log(`On port ${port}`) | |
}) | |
} | |
function factoryFirst(app, port) { | |
setTimeout(() => { | |
let dest = "http://localhost:3022" | |
console.log("Sending request through proxy dest:", dest) | |
axios.get(dest, { | |
proxy: { | |
host: "localhost", | |
port: 3011 | |
} | |
}) | |
.then(response => { | |
console.log(response.data) | |
}, | |
e => { | |
console.log(e) | |
throw e | |
}) | |
}, 500) | |
// runServer(app, port) | |
} | |
function factorySecond(app, port) { | |
app.use("/", (req, res) => { | |
console.log("Original url", req.originalUrl) | |
console.log("Proxy hit. My port is", port) | |
res.send("I'm proxy") | |
// Make requests using `original url` and 'repeating' the parameters. | |
// return proxy("localhost:3012")(req, res) | |
}) | |
runServer(app, port) | |
} | |
function factoryThird(app, port) { | |
app.get("/", (req, res) => { | |
res.send("hi") | |
}) | |
runServer(app, port) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment