Skip to content

Commit

Permalink
Explicitly set the Host header
Browse files Browse the repository at this point in the history
  • Loading branch information
MenGonz committed Jan 20, 2025
1 parent b075712 commit 593a2ff
Showing 1 changed file with 16 additions and 6 deletions.
22 changes: 16 additions & 6 deletions frontdoor-endpoints/frontdoor-api.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@ const axios = require('axios');

const router = express.Router();



// Middleware: Add APIMS subscription key to outgoing requests
const addSubscriptionKey = (req, res, next) => {
const subscriptionKey = process.env.REACT_APP_APIMS_SUBSCRIPTION_KEY; // Store this key in .env file
Expand All @@ -19,29 +17,42 @@ const addSubscriptionKey = (req, res, next) => {
// Proxy logic for all routes under /api
router.all('/*', addSubscriptionKey, async (req, res) => {
try {
// Validate and fetch base URL for APIMS from environment variables
const apimsBaseUrl = process.env.APIMS_BASE_URL;
if (!apimsBaseUrl) {
console.error('[Proxy Middleware] Missing APIMS Base URL');
return res.status(500).send('Internal Server Error: Missing APIMS Base URL');
}

// Construct the APIMS URL, removing the "/api" prefix from the original URL
const targetPath = req.originalUrl.replace('/api', ''); // Remove "/api" from the start of the path
const targetUrl = `${process.env.APIMS_BASE_URL}${targetPath}`;
const targetUrl = `${apimsBaseUrl}${targetPath}`;

console.log(`[Proxy Middleware] Forwarding request to: ${targetUrl}`);

// Make the request to APIMS
const response = await axios({
method: req.method,
url: targetUrl,
headers: req.headers, // Forward all headers, including the subscription key
headers: {
...req.headers, // Forward all headers, including the subscription key
Host: new URL(apimsBaseUrl).host, // Explicitly set the Host header
},
data: req.body, // Forward the request body
});

console.log(`[Proxy Middleware] Received response from APIMS: ${response.status}`);
console.log(`[Proxy Middleware] Response Data:`, response.data);

// Send the response back to the client
res.status(response.status).send(response.data);
} catch (error) {
console.error('[Proxy Middleware] Error during request forwarding:', error.message);

if (error.response) {
// If APIMS responded with an error, forward it to the client
console.error(`[Proxy Middleware] APIMS Response:`, error.response.data);
console.error(`[Proxy Middleware] APIMS Response Status: ${error.response.status}`);
console.error(`[Proxy Middleware] APIMS Response Data:`, error.response.data);
res.status(error.response.status).send(error.response.data);
} else {
// If no response from APIMS, send a generic error
Expand All @@ -51,4 +62,3 @@ router.all('/*', addSubscriptionKey, async (req, res) => {
});

module.exports = router;

0 comments on commit 593a2ff

Please sign in to comment.