Download Image using Fetch API - javascript

I know this question is answered, but I am facing issue while downloading image using Fetch API. Code that I am using to get image.
function downloadImage() {
fetch('https://upload.wikimedia.org/wikipedia/commons/9/98/Pet_dog_fetching_sticks_in_Wales-3April2010.jpg',
{mode: 'no-cors'})
.then(response => response.blob())
.then(blob => {
console.log(blob);
});
}
Here, when I do console.log I get response Blob {size: 0, type: ""}.
Please let me know what I am doing wrong here?

By default fetch uses CORS mode. But when server response doesn't contain 'Access-Control-Allow-Origin' header. It skips response body.
Ironically, you have to set mode as 'no-cors'
to request opaque resources. Opaque responses can't be accessed with JavaScript but the response can still be served or cached by a service worker.
https://developers.google.com/web/ilt/pwa/working-with-the-fetch-api

Related

TypeError on fetch request on "e-raktakosha" web site api

I am new to javascript. I was trying to make an api call.
My code
const options = {
method: 'GET',
headers: {
Authorization: 'Basic dW5kZWZpbmVkOnVuZGVmaW5lZA==',
'content-type': 'application/json',
}
};
fetch(
'https://www.eraktkosh.in/BLDAHIMS/bloodbank/nearbyBB.cnt?hmode=GETNEARBYSTOCKDETAILS&stateCode=21&districtCode=378&bloodGroup=all&bloodComponent=11&lang=0',
options
)
.then((response) => response.json())
.then((response) => console.log(response))
.catch((err) => console.error(err));
but I encountered with an error saying
Error: Failed to fetch
This api call works perfectly with Hoppscotch
If I try to hit the url right on my url bar, it also works fine.
Any help is strongly appreciated. Thank you from Manoranjan
As other People already mentioned, you can't pass a Body when doing a GET HTTP call, instead you can pass Query Params
Notice this part on the URL
hmode=GETNEARBYSTOCKDETAILS&stateCode=21&districtCode=378&bloodGroup=all&bloodComponent=11&lang=0
Still looking into the code it seems the server have a cors policy, look at this sandbox
See this codesandbox -> https://codesandbox.io/s/peaceful-mcclintock-exuzol?file=/src/index.js
Summary:
GET accept body/payload but it could cause errors, see https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/GET
Using the Web API (new headers, new request) for doing the HTTP call
It is better to just avoid sending payloads in GET requests.
Please don't use body with a get request. The GET request is purely meant to collect back data from server, which allows you to sent Queries, not data on the request. Just remove body:'false' or use body:false. The best way is to remove the body from your request so unexpected input is not sent via this GET request.

Problem using fetch to retrive data from an API - works in Postman

I am trying to access an API using JavaScript. When accessing it using Postman everything works fine. I can make a GET request and it sends back the correct data. However when I try to do the same using fetch(), it either returns nothing or gives me an error (depending on the mode I am using).
<script>
async function get_page() {
const response = await fetch("MY_LINK", {
method:'GET',
mode:'cors',
redirect:'follow'
});
return response;
}
get_page().then(data => console.log(data)).catch(err => console.log(err));
</script>
The above throws:
Access to fetch at 'MY_LINK' 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.
If I change the mode to no-cors, I get a reply but cannot seem to find the returned message (the body attribute is null) in it, that I am seeing when I use Postman.
In a browser, with your function, this worked:
get_page().then(response => response.json()).then(data => console.log(data)).catch(err => console.log(err));
Full code (poke api :)
async function get_page() {
const response = await fetch('https://pokeapi.co/api/v2/pokemon/ditto', {
method:'GET',
mode:'cors',
redirect:'follow'
});
return response;
}
get_page().then(response => response.json()).then(data => console.log(data)).catch(err => console.log(err));
Note about CORS:
Tested on the browser console while visiting:
https://pokeapi.co/ -> ok
https://developer.mozilla.org -> FAIL (Content Security Policy)
https://www.google.com/ -> ok
so it pays to see your server code as well
This is the result of my code:

i am using window.fetch for downloading file , but is generating error file on server not on local

function download(id) {
$.get(base_url + "account/download/" + id, function (data) {
var data = JSON.parse(data);
if (data.code == 1) {
console.log(data)
//data.filePath = "https://s3.amazonaws.com/stores-products/8c0123ef4a1d685bbf50582ffb461573.jpg"
fetch(data.filePath, { mode: 'no-cors', method: 'GET' })
.then(resp => resp.blob())
.then(blob => {
console.log(blob)
const url = window.URL.createObjectURL(blob);
console.log(url)
const a = document.createElement('a');
//a.style.display = 'none';
a.href = url;
a.download = data.fileName;
document.body.appendChild(a);
a.click();
a.remove();
window.URL.revokeObjectURL(url);
})
.catch(() => bootbox.alert("Unable to Download File"));
}
else if (data.code == 0) {
bootbox.alert(data.msg);
}
});
}
under get api call I am using fetch with url of amazon s3 , its working fine on local but it generating error file on server , please review my code and let me know the issue in this code. I did not getting any error message , but downloaded file , when I am opening it show error to load file.
In order to be able to fetch resources cross-origin you need to understand and properly configure CORS headers, i.e. the server needs to send the right Access-Control-Allow-Origin and Access-Control-Allow-Methods.
Otherwise browser security will prohibit the request.
Trying to circumvent this with {mode: 'no-cors'} does not work as one might expect: although 'no-cors' will ignore the CORS headers of the server the response content will then be inaccessible to your javascript code, see the documentation for Request.mode:
no-cors — Prevents the method from being anything other than HEAD, GET or POST, and the headers from being anything other than simple headers. If any ServiceWorkers intercept these requests, they may not add or override any headers except for those that are simple headers. In addition, JavaScript may not access any properties of the resulting Response. This ensures that ServiceWorkers do not affect the semantics of the Web and prevents security and privacy issues arising from leaking data across domains.
This is due to the resulting Response's type being opaque preventing you from accessing its actual contents.
For further explanation see this excellent answer to a similar question.
So what you need to do is to use {mode: 'cors'} and have the server appropriately configured to allow for cross-origin requests from your frontend domain.

Need a way to enable CORS in vueJS [duplicate]

This question already has answers here:
No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API
(26 answers)
Closed 2 years ago.
I am new to vueJS and version using is 2.0. I need to fetch some JSON data from url. Using javacsript fetch methods to get the data from URL. below is my code,
function getValue() {
const requestOptions = {
method: "GET",
header: {"Access-Control-Allow-Origin": "GET"}
};
fetch("http://api.plos.org/search?q=title:DNA", requestOptions)
.then(
(response) => {
console.log(response.json());
}
);
}
getValue();
I am getting CORS issue like,
Access to fetch at 'http://api.plos.org/search?q=title:DNA' from origin 'http://localhost:8080' 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.
I tried all the possibilities which available in stack-overflow. But no luck.
Any help would be much appreciated.
JSFiddle link - https://jsfiddle.net/m45hsekf/
Did you tried to set the mode to no-cors like the error suggests to you?
set the request's mode to 'no-cors' to fetch the resource with CORS
disabled.
I have tested it and it works:
const requestOptions = {
method: "GET",
mode: "no-cors"
};
So the request looks like this:
fetch("http://api.plos.org/search?q=title:DNA", {
mode: "no-cors"
})
.then(response => response.json())
.then(result => {
console.log(result);
});
CORS should be enabled at server level like node or java application.
Access-Control-Allow-Origin : "test-client.com" or use "*"(not recommended). Then allow this value at the server
Get is your http method not the origin value
To enable in node use this line
res. header("Access-Control-Allow-Origin", "*"); // again * is not a best practice. Please accept this as answer too
Refer to the url below for more info
https://dzone.com/articles/cors-in-node
when i have problems while i develop, i use crhome extension called CORS UNBLOCK, then i can test my api, and when i deploy to final server, always is in the same domain then i havent cors ploblem

Cors issue with third party api

I am struggle with getting data from third party api on browser. 'https://www.coinexchange.io/api/v1/getmarkets'
I set mode:'no-cors' as option because it seems the response header does not include Access-Control-Allow-Origin. But mode: no-cors does not allow me to access to the data.
function callApi({ url }) {
return fetch(url, {
mode: 'no-cors'
})
.then(response => {
if (!response) {
}
return response.json()
})
.then(response => {
const camelizedJson = camelizeKeys(response)
return Object.assign({},
normalize(camelizedJson),
)
})
}
The response returns type: opaque like this image and response headers is this
I believe mode: no-cors works like sending GET request from HTML img tag so I can not use the information.
Is there any way to access to the third party API whose response header does not have Access-Control-Allow-Origin? How am I supposed to call third party public api?
If you have any ideas to fix this problem, please let me know! Thank you

Categories