Skip to content

Instantly share code, notes, and snippets.

@chwaee
Created October 4, 2023 05:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chwaee/37fe9b22c65e6d8e30345aba067fdf4a to your computer and use it in GitHub Desktop.
Save chwaee/37fe9b22c65e6d8e30345aba067fdf4a to your computer and use it in GitHub Desktop.
Node.js with express middleware for K8s nginx ingress controller sidecar
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