It’s just a simple “trick” I came across while working at my latest project.
What we are sometimes faced with when working with an API hosted on another server is something named CORS.
A really simple solution is to configure a reverse proxy (NGINX / Apache) if you have a web server (if you don’t you can easily set up a local WAMP / LAMP server for dev purposes).
And setting up a reverse proxy in NGINX is much easier than doing it in Apache as it only takes a couple of lines.
I added this to server { }
in my default config (/etc/nginx/sites-available/default):
location /api/ { proxy_set_header Authorization "Basic ZGV2OmRldg=="; proxy_pass http://url.to.the.api/api/; }
The simplest proxy wouldn’t need the proxy_set_header part but in my case I needed it because there was HTTP authentication in place. “ZGV2OmRldg==” is “username:password” Base64 encoded (without quotes).
Now, accessing localhost/api/ would be the same as accessing url.to.the.api/api/, which means that if you issue a GET request to localhost you are going to get one back from localhost instead of from across the internet – bye bye CORS!
Happy developing!