Reverse proxy middleware #163
ahmaddie1378
started this conversation in
General
Replies: 1 comment
-
Maybe you can try such a method by deriving it and adapting it to your structure: import * as HyperExpress from 'hyper-express'
import axios from 'axios'
let server = new HyperExpress.Server()
let router = new HyperExpress.Router()
const service = {
host: '0.0.0.0',
port: 3001,
prefix: 'auth',
protocol: 'http',
}
const proxyMiddleware = async (req: any, res: any) => {
const target = `${service.host}:${service.port}`
const targetUrl = `${service.protocol}://${target}${req.url.replace(`/api/${service.prefix}`, '')}`
console.log(`Proxying request to ${targetUrl}`)
try {
const response = await axios({
method: req.method,
url: targetUrl,
headers: req.headers,
data: req.body,
})
res.status(response.status)
Object.entries(response.headers).forEach(([key, value]) => {
res.setHeader(key, value)
})
res.send(response.data)
} catch (error) {
console.error('Proxy error:', error)
res.status(500).send('Internal Server Error')
}
}
router.get('/', (req, res) => {
res.send('Base Route')
})
router.get('/v1', (req, res) => {
res.send('API')
})
router.use(`/v1/service`, async (req, res) => {
await proxyMiddleware(req, res)
})
router.all('*', (req, res) => {
res.status(404).send('404 Not Found')
})
server
.use(router)
.listen(3000)
.then((socket) => {
console.log('App started on port: 3000')
})
.catch((error) => console.log('Failed to start webserver;' + error)) |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Any reverse proxy middleware for hyper express?
I look up online didn't find something
Beta Was this translation helpful? Give feedback.
All reactions