Setting Up a Proxy Server with Express

February 20, 2015

The Problem:

I am working on a project that uses BreweryDB. While trying to load some data from the API, I encountered a problem: the API doesn't support JSONP. This leads to a CORS issue when I attempt to fetch data directly using Angular:

XMLHttpRequest cannot load [https://api.brewerydb.com/v2/.](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:

To avoid exposing my API key, I needed to set up an intermediate proxy. Below are the step-by-step instructions for setting up a proxy using Node.js and Express.

Step 1: Install Express and Request

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

Step 2: Create a server.js File

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

Step 3: Set Up the Route (replace API_KEY with your actual 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: Set Up the Port

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

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

Open your browser and navigate to http://localhost:3000/api. You should be able to see the JSON object and log it 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"

If you encounter any problems, feel free to send me an email. ☺


Profile picture

Software development professional with expertise in application architecture, cloud solutions deployment, and financial products development. Possess a Master's degree in Computer Science and an MBA in Finance. Highly skilled in AWS (Certified Solutions Architect, Developer and SysOps Administrator), GCP (Professional Cloud Architect), Microsoft Azure, Kubernetes(CKA, CKAD, CKS, KCNA), and Scrum(PSM, PSPO) methodologies. Happy to connect