How To Deal With CORS Problems

mhrsntrk

mhrsntrk / January 22, 2021

When trying to reach an API or service from localhost can be really painful due to CORS policies. This wonderful cors-anywhere repo here to rescue. You can literally deploy your own on HEROKU under 2 minutes by using below instructions.

  1. Open your HEROKU account and click Create new app.
  2. Enter an App name and choose a region from Choose a region list.
  3. Install Heroku CLI, or just brew tap heroku/brew && brew install heroku if you have Homebrew installed.
  4. Open a terminal session and go to a file that you want to clone the cors-anywhere repo.
  5. Enter the below comments.
cd cors-anywhere/
npm install
heroku login
git init
heroku git:remote -a <app_name>
git add .
git commit -am "initial commit"
git push heroku master

If everything went okay, your cors-anywhere clone will be deployed to your HEROKU account. You can access it via `https://<app_name>.herokuapp.com/`.

You can directly add `https://<app_name>.herokuapp.com/` front of the link and it will be proxied. There is a example code below for the reference.

```export default async function getSomething() {

  const proxyurl = "https://<app_name>.herokuapp.com/";

  const response = await fetch(
    proxyurl +
      "https://pro-api.someapi.com/v1/",
    {
      headers: {
        "API_KEY": `apikey`,
      },
      json: true,
    }
  );

  const json = await response.json();

  return json;
}