Redirecting API calls

Redirecting API calls
October 13, 2017  | 1 min read

Have you ever tried to redirect API calls? This is a simple way to change api server url without any interference in current code base.It may take a lot of effort to set up correctly your local dev environment especially when you work with big big project (eg. enterprise-class).

But having a separate environment with all the services and infrastructure is not always a necessity. For example front-end developers needs simply an access to js, CSS and HTML files only.

Redirecting API calls

The other thing is that not every project is built in a way you can manually change the API server URL. But as I mentioned earlier, there is a quick way to achieve this without any interference in the current codebase.

What you have to do is to set up a 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.

Sounds simple? Yeah, and it is simple!

I suggest using a node.js based solution as you probably already using it to build automation or package management. My chose was ExpressJs. That is a web development framework for node.js which allows us to quickly set up a full-functioning web server.

Redirecting API calls - step by step instructions

  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: '',
    changeOrigin: true})); app.listen(3000, () => {console.log('Listening on: http://localhost:3000');});
  3. Run your express server using the command:
    node server.js
  4. Open your browser and enter:

And that's it! Now you can work on a web interface without setting up the whole environment. If you have any questions, comment below the post.

Expand your knowledge with our tech & development posts!