Building a proxy server as a workaround for CORS error

Rohan Krishna Ullas
2 min readAug 22, 2021

Ever felt frustrated that your perfectly valid call to an API has been blocked by CORS error? If yes, then let's get started with building a solution to solve it.

Photo by Taylor Vick on Unsplash

I recently had to deal with the CORS error after my API call to nlpcloud API was being blocked by my browser’s CORS policy.

This is how the error looked like.

While searching for solutions online, I came across this brilliant article by David Katz. In that article, he proposes three solutions to overcome this error, and in my case, I used the third approach of deploying my own proxy server to fetch requests successfully. In this approach, we’re taking advantage of the fact that the same-origin policy is not enforced in server-server communication.

Building the proxy server

Here, I’ll be using Flask framework to build the proxy server.

First, let’s set up the virtual environment.

C:\Users\Kakarot> virtualenv venv1 && call venv1/Scripts/Activate

Next, we’ll be installing the prerequisite libraries from requirements.txt .

Note: trafilatura and nlpcloud libraries are specific to my use case. I’m making use of trafilatura and nlpcloud for text extraction and summarization respectively.

(venv1)C:\Users\Kakarot> pip install -r requirements.txt

Here’s the python code to run the server. I have stored the API token in a .env file from which I load the token in the code.

NOTE: the objective of making an API call to /getSummary endpoint is to get the summary of the webpage referenced by the URL as a string response.

Now, once I start the app and make a fetch API call to the localhost address where the app is running, I will get the response back without the CORS error.

C:\Users\Kakarot> python app.py

Try copy-pasting this code in the chrome developer console to see the response.

NOTE: Lines 7–32 deal with getting the data from ReadableStream. This might not be needed for your case and hence can be removed. For more reference, refer source.

Now, the next step will be to deploy the proxy server using a cloud hosting platform so that it can be accessed from any machine.

--

--

Rohan Krishna Ullas

Caught in an endless loop of building and breaking stuff 😄 SDE-1 @ Microsoft