1

I am completely inexperienced with JavaScript but I am working on a website that needs to pull updated stats from an API. After doing some reading and following a few tutorials, I'm still pretty lost. Any help would be appreciated.

Here is what I have and it's not working and I'm not sure if I'm even on the right path.

JS

const api_url = 'https://plutonium.pw/api/stats'
async function getData() {
  const response = await fetch(api_url);
  const data = await response.json();
  const { bans } = data;
  
  document.getElementById("bans").textContent = bans;
  console.log(bans);
  
}

getData();

HTML

<!doctype html>
<html>

<head>
    <title>Test Page</title>
</head>

<body>
    <p>bans: <span id="bans"></span></p>
</body>

</html>

CODEPEN

Shahnawaz Hossan
  • 2,695
  • 2
  • 13
  • 24
Bob Smith
  • 23
  • 6
  • Any error in console ? – Shivam Shukla Dec 27 '20 at 15:55
  • 2
    You have a CORS network error in the console which means that API is not reachable from client side javascript. You will need to use a CORS proxy either on server you control or a third part service to make the request through – charlietfl Dec 27 '20 at 15:58
  • I'm not seeing that error. But I'll look into it. – Bob Smith Dec 27 '20 at 16:02
  • See https://stackoverflow.com/questions/10636611/how-does-access-control-allow-origin-header-work – charlietfl Dec 27 '20 at 16:04
  • Adding a CORES proxy before the url did work. – Bob Smith Dec 27 '20 at 16:27
  • 2
    what do you mean by """not working""", what is the exact behavior? Are there any logs on the console? Also, you're calling an async function without attaching any appropriate handlers using `.then` and `.catch` – Chase Dec 27 '20 at 16:29
  • Does this answer your question? [How does Access-Control-Allow-Origin header work?](https://stackoverflow.com/questions/10636611/how-does-access-control-allow-origin-header-work) – Heretic Monkey Dec 27 '20 at 16:34

1 Answers1

0

As pointed out by @charlietfl there was a CORES related error and adding a proxy fixed the issue. The new js is as follows:

const api_url = 'https://cors-anywhere.herokuapp.com/https://plutonium.pw/api/stats'
async function getData() {
  const response = await fetch(api_url);
  const data = await response.json();
  const { bans } = data;
  
  document.getElementById("bans").textContent = bans;
  console.log(bans);
  
}
Bob Smith
  • 23
  • 6
  • It's called CORS, and your question made no mention of the error. While I respect that @charlie's guess was a good one, this question is unlikely to help anyone else, considering the sheer number of CORS-related questions we receive on a daily basis. – Heretic Monkey Dec 27 '20 at 16:34