Created
September 3, 2023 14:43
-
-
Save zapkub/76d68804de89bc599debed1646c7a852 to your computer and use it in GitHub Desktop.
Setup multi port with reverse proxy
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
import * as Express from 'express'; | |
import { Router } from 'express' | |
import { createProxyServer } from 'http-proxy'; | |
// ส่วนนี้คือ http server ของ front-ui | |
const frontendRouter = Router(); | |
frontendRouter.all('/', (req, res) => { | |
res.redirect('/index.html') | |
}) | |
frontendRouter.get('/index.html', (req, res) => { | |
// html frontend page | |
res.status(200).send(` | |
<html> | |
<body>Hello <span id='response'>waiting for response</span> | |
<script> | |
fetch('/api/version').then((res) => res.text()).then((payload) => { document.getElementById('response').innerHTML = payload }) | |
</script> | |
</body> | |
</html>`) | |
}) | |
const frontendExpress = Express(); | |
frontendExpress.use(frontendRouter); | |
frontendExpress.listen(3000) | |
// ส่วนนี้คือ http server ของ backend-ui | |
const backendRouter = Router(); | |
backendRouter.get('/api/version', (req, res) => { | |
res.json({version: "1.0.0"}) | |
}) | |
const backendExpress = Express(); | |
backendExpress.use(backendRouter); | |
backendExpress.listen(3200) | |
// ส่วนนี้คือส่วน reverse proxy คุณอาจจะแยกทุกไฟล์ให้มี entrypoint แยกกัน และมี entrypoint 1 file สำหรับ development purpose | |
// ที่ bind ทุกอย่าง และมี reverse proxy ในการ forward ไปที่ port ที่ถูกต้อง | |
const proxyExpress = Express(); | |
const proxy = createProxyServer(); | |
proxyExpress.all('/api/*', (req, res) => { | |
proxy.web(req, res, {target: 'http://localhost:3200'}) | |
}) | |
proxyExpress.all('/*', (req, res) => { | |
proxy.web(req, res, {target: 'http://localhost:3000'}) | |
}) | |
// เข้า browser ที่ http://localhost:8080 จะพบว่า | |
// http://localhost:8080/api/version จะถูก forward ไปที่ backendExpress router | |
// http://localhost:8080/ จะถูก forward ไปที่ frontend-ui และถูก redirect ไปที่ http://localhost:3000/index.html | |
proxyExpress.listen(8080) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment