Created
October 4, 2023 05:45
-
-
Save chwaee/37fe9b22c65e6d8e30345aba067fdf4a to your computer and use it in GitHub Desktop.
Node.js with express middleware for K8s nginx ingress controller sidecar
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 express = require('express'); | |
const app = express(); | |
const axios = require('axios'); | |
const PORT = 3000; | |
const TARGET_URL = 'http://main-app-service:8080'; // Replace with your main application's service URL | |
app.use(express.json()); // for parsing application/json | |
// Middleware to log request body | |
app.use((req, res, next) => { | |
console.log('Request Body:', req.body); // Log the request body | |
next(); // Move to the next middleware (proxying the request in this case) | |
}); | |
// Proxying the request to the main application | |
app.all('*', async (req, res) => { | |
try { | |
const response = await axios({ | |
method: req.method, | |
url: `${TARGET_URL}${req.path}`, | |
data: req.body, | |
headers: req.headers | |
}); | |
res.status(response.status).send(response.data); | |
} catch (error) { | |
res.status(error.response?.status || 500).send(error.response?.data || {}); | |
} | |
}); | |
app.listen(PORT, () => { | |
console.log(`Server is running on port ${PORT}`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment