+ 1
Api image on website
Hi everyone, I have this API (https://some-random-api.ml/img/dog) and I'd like to make the image appear on my website... How can I do that?? Can it be done? Thank you in advanceđ
2 Answers
+ 4
Something like this could work except you need to update your API to respond with
Access-Control-Allow-Origin: *
in its HTTP response headers.
fetch('https://some-random-api.ml/img/dog')
.then(response => response.json())
.then(function(response) {
let img = document.createElement('img');
img.setAttribute('src', response.link);
document.querySelector('body').appendChild(img);
});
If you run that from a file like https://some-random-api.ml/displayImage.html, you won't need to worry about Access-Control-Allow-Origin. It becomes a concern only when browser-based JavaScript sends requests to other host names. "origin" basically means host/domain name.
Your API response says that the server is cloudflare so this article might be useful detail explaining the CORS header:
https://support.cloudflare.com/hc/en-us/articles/200308847-Using-cross-origin-resource-sharing-CORS-with-Cloudflare
+ 1
Accessing api using backend server script like Node.js or PHP.
https://code.sololearn.com/cZh2w6V5aH8r/?ref=app