0

The following python request is grabbing data from a paid API using private API key, and the fetch is working just fine:

import requests

api_key = 'our_private_api_key'
headers = { 'x-api-key': api_key }
params = {}
endpoint = 'our_api_endpoint_url'
resp: dict = requests.get(endpoint, headers=_headers_builder(headers), params=params).json().get('response', {})
resp_data = resp.get('data', None)

When fetching locally in Javascript (React App) using axios, we attempt with similar code, but in JavaScript (with the help of react-query's useQuery):

import { useQuery } from 'react-query';
import axios from 'axios'

async function fetchLiveData() {
    const api_key = 'our_private_api_key';
    const endpoint = 'our_api_endpoint_url';
    const { data } = await axios.get(endpoint, { headers: { 'x-api-key': api_key } });
    return data;
}

const { data, error, isError, isLoading: isLoading25 } = useQuery('posts', fetchLiveData);

...however the following error is thrown from this fetch.

Access to XMLHttpRequest at 'endpoint' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Is this a localhost problem, or is some parameter being omitted from the axios fetch, or is it a permissions issue with the API provider? Or something else? How can we go about troubleshooting this issue?

Canovice
  • 9,012
  • 22
  • 93
  • 211
  • I'm no expert on Python, but I'm guessing this has to do with Python not being used in a browser environment, and so CORS is not respected by Python, but it is in your browser. If you can modify the headers your `localhost` server sends, include `'Access-Control-Allow-Origin': ['*']` (I might not have the syntax exactly right) – Slbox Mar 17 '22 at 23:08
  • [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) controls *browser* access to a sites resources – Bravo Mar 17 '22 at 23:11

1 Answers1

0

I guess that the python env is outside the browser and the browsers block origin requestes and your client-side code don't have anything to do, the API is responsible of handling this issue by adding an http header "Access-Control-Allow-Origin: YOUR_DOMAIN OR *" and you said it's a paid API and you can't handle this so I assume that they have a console dashboard and I think in their settings you can configure ( whitelist ) the accepted origins and there you can add your origin, localhost or allow all origins.