0

I am very new to JAVASCRIPT so please forgive me if this is a basic question.

I am making a very simple api call:

  const getWorldTotal = async () => {
        const response = await fetch('https://health-api.com/api/v1/covid-19/total');
        const myJson = await response.json();
        console.log(myJson)
      }
      getWorldTotal();

I keep getting an error saying:

Access to fetch at 'https://health-api.com/api/v1/covid-19/total' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

So then I did the following:

  const getWorldTotal = async () => {
        const response = await fetch('https://health-api.com/api/v1/covid-19/total',{
          mode: 'no-cors'
        });
        const myJson = await response.json();
        console.log(myJson)
      }
      getWorldTotal();

But I still get the following error:

Uncaught (in promise) SyntaxError: Unexpected end of input
    at getWorldTotal on line 42

line 42 is the following const myJson = await response.json();

I am not sure what I did wrong?

2 Answers2

0

You can use this

const response = await fetch('https://cors-anywhere.herokuapp.com/https://health-api.com/api/v1/covid-19/total');
const myJson = await response.json();
console.log(myJson);
iamhuynq
  • 5,357
  • 1
  • 13
  • 36
  • you can see in here https://stackoverflow.com/questions/43871637/no-access-control-allow-origin-header-is-present-on-the-requested-resource-whe – iamhuynq Mar 18 '20 at 03:36
  • Not sure if this will work i get Uncaught SyntaxError: await is only valid in async function –  Mar 18 '20 at 03:36
  • so add `async` to your `getWorldTotal` function – iamhuynq Mar 18 '20 at 03:38
0

Although you got your solution which is ok but I would like to add why you are getting error.

when you add

{mode: 'no-cors'}

In this case you will not get cors error at browser side but also you will not get response. So that means after getting response when you try to execute below line:

const myJson = await response.json();

you will obviously get the syntax error because your response body is null (you can also see response body through debugging of your code ) and trying to convert null into json.

Solution: 1. First solution is to wrap you url into with https://cors-anywhere.herokuapp.com which is already mentioned above.

  1. Ask server to add response header:

    headers: {Access-Control-Allow-Origin':'*'}

  2. If you are using node then install node package cors-anywhere
Jeet Kumar
  • 555
  • 3
  • 12