Redirecting API calls

13.10.2017

Paweł Sadowski
Software Developer
Paweł Sadowski

Have you ever tried to redirect API calls? When you are working on enterprise class project using microservices architecture it might take a lot of work and skills to set up your local dev environment. On top of that, not all developers really need own separate environment including all of services and infrastructure. If you are front-end developer all you need is free access to js, css and html files.

If your project wasn’t built in a way you can manual change api server url there is a quick way to achieve this without any interference in current code base. What you have to do is to setup small web server that will serve static files like images, scripts, and html from your hard drive and will redirect all api calls to some hosted instance. I suggest using nodejs based solution as you probably already using it for build automation or package management. My chose was ExpressJs. That is web development framework for nodejs which allows to quickly setup full functioning web server.

1. The first step is to install express and express proxy middleware. So open your console in your project directory and type in:

npm install express --save-dev 
npm install express http-proxy-middleware --save-dev 

2. Create server.js file in your wwwroot directory and type in code:

const express = require('express');
const proxy = require('http-proxy-middleware');
const apiServerUrl = '';
const app = express();

app.use('/', express.static(__dirname + '/'));  //setup static files serving

app.use('/api', proxy({							//setup proxy to redirect all '/api' requests
  target: 'http://some-hosted-api-server.com',
  changeOrigin: true
})); 

app.listen(3000, () => {
  console.log('Listening on: http://localhost:3000');
});

3. Run your express server using command:

node server.js

4. Open your browser and enter:

http://localhost:3000/

Now you can work on web interface without setting up the whole environment.