Reputation: 3129
I am trying to fetch data from this address data source
and am getting errors, the code I am writing is
(function(){
async function GetCovidNumbers(){
const url = "api.opencovid.ca/summary?loc=canada&date=01-09-2020";
//debugger;
const data = await fetch(url);
const response = await data.json();
console.log(response);
}
GetCovidNumbers();
})();
The errors I am getting are
one is giving me a 404 error but if I place the url in the browser then I get the data and the other error is
Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
I have tried adding http:// in front of the url and even https:// and that doesn't work.
So I am obviously doing something wrong, anyone see what it is?
Upvotes: 2
Views: 32
Reputation: 25659
You need to specify the protocol (http://
or https://
), because otherwise, it will be treated as a relative URL.
Now, I see that the API does not support HTTPS. If your site is using HTTP, this is not a problem. But if your site is using HTTPS, then the browser will block the request because the API is not secure.
In this case, you can use an HTTPS proxy to make the request. CORS Anywhere is such a service.
Demo (takes a couple of seconds to load):
async function GetCovidNumbers() {
const corsPrefix = "https://cors-anywhere.herokuapp.com/";
const url = corsPrefix + "http://api.opencovid.ca/summary?loc=canada&date=01-09-2020";
const data = await fetch(url);
const response = await data.json();
console.log(response);
}
GetCovidNumbers();
Upvotes: 2