0

I am trying to call an api in the react js but no matter how i do it i always am getting error. I tried to call it using axios like this:

axios
      .get("http://goldpricez.com/api/rates/currency/PKR/measure/ounce?X-API-KEY=API-KEY HERE")
      .then(function(response) {
          console.log(response);
      })
      .catch(function(error) {
        console.log(error);
      })
      .finally(function() {
        // always executed
      });

I also tried using fetch to do this:

   fetch(
      "http://goldpricez.com/api/rates/currency/PKR/measure/ounce?X-API-KEY=API-KEY-HERE")
      .then(function(response) {
        console.log(response);
      })
      .catch(function(error) {
        console.log("Looks like there was a problem: \n", error);
      });

but both ways ended with the same error. After searching the stackoverflow i found a couple of same queries but in all cases they had the server side in control too. In my case I am using a third party library so i cannot change Access-Control-Allow-Origin even if i wanted to on the server side. For testig purposes i am using an extension of chrome that some how bypass this error and i get the response. Is there anyother thing i can do to make it work cause in production not all users might be using the chrome and even if they do its highly unlikely they will be using the cors extension.

Abdulmoiz Ahmer
  • 1,953
  • 17
  • 39
  • 1
    You can run own CORS proxy. For details, see the *“How to use a CORS proxy to get around “No Access-Control-Allow-Origin header” problems”* section of the answer at https://stackoverflow.com/a/43881141/441757. But note that if that `http://goldpricez.com` API endpoint requires you to include the value of your secret API key as a query parameter in the request URL, then if you make requests to that API endpoint from frontend JavaScript code running in a browser, you’re exposing your secret API key to anybody who knows how to use browser devtools to inspect your web app. – sideshowbarker Oct 20 '19 at 07:57
  • The api require's the secret key instead of a token can't change that. How can i get around it and not expose my api key. – Abdulmoiz Ahmer Oct 20 '19 at 08:02
  • 1
    The only way is to make the request from your backend server code rather than making the request from your frontend JavaScript code. – sideshowbarker Oct 20 '19 at 08:03
  • After prefixing it with the proxy it started working but what about the production will i still have to use the proxy while in production mode or not – Abdulmoiz Ahmer Oct 20 '19 at 08:10
  • Yeah you would still need to use the proxy in production — or else, as I said, make the request from your backend code instead. – sideshowbarker Oct 20 '19 at 08:22
  • ok thankyou i am doing it in express. – Abdulmoiz Ahmer Oct 20 '19 at 08:44

0 Answers0