0

I'm attempting to proxy a remote, protected resource.

The proxy doesn't work, so I'm guessing that I have not configured it correctly.

server.js:

const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
    
const app = express();
app.use(express.json());
    
app.use('/api/employees', 
    createProxyMiddleware(
        {
            target: `https://api.bamboohr.com/api/gateway.php/${process.env.BAMBOOHR_API_SUBDOMAIN}/v1/employees/directory`,
            changeOrigin: true,
            headers: {
                Accept: 'application/json',
                Authorization: "Basic " + Buffer.from(process.env.BAMBOOHR_API_KEY + ":password").toString('base64')
            },
            logger: console,
        }
    )
);
    
app.listen(3030, 'localhost', () => {
    console.log('Service running');
});

When I try to contact the local URL, I get a 404 error:

No webpage was found for the web address: http://localhost:3030/api/employees

package.json:

{
  "dependencies": {
    "express": "^4.18.2",
    "http-proxy-middleware": "^2.0.6"
  }
}

What am I missing?

craig
  • 25,664
  • 27
  • 119
  • 205

2 Answers2

0

Everything looks fine except I would pass secure: true to the createProxyMiddleware config since the external resource is HTTPS.

Wesley LeMahieu
  • 2,296
  • 1
  • 12
  • 8
0

I needed to change the target to reference the common base of the API and add a pathRewrite to remove /api/bamboohr:

app.use('/api/bamboohr', createProxyMiddleware({
    target: `https://api.bamboohr.com/api/gateway.php/${process.env.BAMBOOHR_API_SUBDOMAIN}/v1`,
    changeOrigin: true,
    headers: {
        Accept: 'application/json',
        Authorization: "Basic " + Buffer.from(process.env.BAMBOOHR_API_KEY + ":password").toString('base64')
    },
    pathRewrite: {
        [`^/api/bamboohr`]: '',
    },
}));

This allows me to map http://localhost:3000/api/bamboohr --> https://api.bamboohr.com/api/gateway.php/{subdomain}/v1

Without the pathRewrite entry, attempting to contact http://localhost:3000/api/bamboohr/employee/directory would result in https://api.bamboohr.com/api/gateway.php/{subdomain}/v1/api/gateway.php/subdomain/v1/api/bamboohr/employees/directory.

craig
  • 25,664
  • 27
  • 119
  • 205