Setup proxy server with Express

The problem:

I am working on a project using BreweryDB. I was trying to load some data from the API, but they don’t support jsonp. There is a CORS issue if I directly fetch data using Angular:

XMLHttpRequest cannot load https://api.brewerydb.com/v2/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

My solution:

I don’t want to expose my API key, so I have to setup an intermediate proxy. The following code illustrates step by step on how to setup a proxy using node/express.

Step 1: Install express and request

npm install express --save npm install request --save

Step 2: Create server.js

var express = require('express'); 
var request = require('request');
var app = express();

Step 3: Setup the route (replace API_KEY with your API key)

app.get('/api', function(req, res){ 
request('https://api.brewerydb.com/v2/?key=' + API_KEY, function (error, response, body) {
if (!error && response.statusCode === 200) {
console.log(body);
res.send(body);
}
});
});

Step 4: Setup the port

app.listen(3000); 
console.log('Server running on port %d', 3000);

Step 5: Start the server (node server.js)

Open your brower at http://localhost:3000/api, you should be able the get the json object and log in your browser console:

"message":"Request Successful", 
"data":"You have reached the BreweryDB.com API. For access, check out http://www.brewerydb.com/developers",
"status":"success"

Send me an email if you have any problem ☺


Originally published at victorleungtw.com on December 27, 2014.

By Victor Leung

Experience in software development, consulting services and technical product management. Understanding of business and technology with an MBA in Finance and a Master degree in Computer Science. AWS Certified Solution Architect with experience in building products from scratch and serving as a charismatic leader.

Leave a comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.