I am using Promise to log the response from an api. But everytime the body is logging in as null. Most probably due to async call
For calling api from fetch.
function getDetails(url){
return new Promise((resolve, reject) => {
fetch(url, {mode: 'no-cors'}).then(res => {
resolve(res);
}, error => {
console.log(err);
})
})
}
var u = ".json";
getDetails(u).then(function(resp){
console.log(resp);
})
I expect the response of the api in console
I am using Promise to log the response from an api. But everytime the body is logging in as null. Most probably due to async call
For calling api from fetch.
function getDetails(url){
return new Promise((resolve, reject) => {
fetch(url, {mode: 'no-cors'}).then(res => {
resolve(res);
}, error => {
console.log(err);
})
})
}
var u = "https://get.geojs.io/v1/ip/country.json";
getDetails(u).then(function(resp){
console.log(resp);
})
I expect the response of the api in console
Share Improve this question edited Jun 8, 2019 at 11:53 mgarcia 6,3353 gold badges23 silver badges42 bronze badges asked Jun 8, 2019 at 7:57 Ayush KoshtaAyush Koshta 1031 gold badge1 silver badge10 bronze badges 5-
fetch()
already returns aPromise
, hencenew Promise(...)
is unnecessary – Andreas Commented Jun 8, 2019 at 8:00 - If I just do fetch and .then() in the function without returning anything still the body is null – Ayush Koshta Commented Jun 8, 2019 at 8:03
-
fetch()
returns aResponse
object. – Andreas Commented Jun 8, 2019 at 8:03 - function getDetails(url){ fetch(url, {mode: 'no-cors'}).then(res => { console.log(res) ; },error => { console.log(err); }) } – Ayush Koshta Commented Jun 8, 2019 at 8:05
- Possible duplicate of Trying to use fetch and pass in mode: no-cors. Don’t use 'no-cors' mode. – sideshowbarker ♦ Commented Jun 8, 2019 at 10:23
1 Answer
Reset to default 4fetch()
already returns a Promise
so get rid of the new Promise(...)
part
function getDetails(url) {
return fetch(...).then(...);
}
fetch()
returns a Response
object and not something that has already been parsed for you. You have to call .json()
on it to get the response parsed by JSON.parse()
.
function getDetails(url) {
return fetch(url, {mode: 'no-cors'}).then(response => response.json());
}
This should already work, but with your setup will throw a syntax error:
SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data
To get this fixed remove mode: 'no-cors'
Adding it all together will give us:
function getDetails(url) {
return fetch(url).then(response => response.json());
}
var u = "https://get.geojs.io/v1/ip/country.json";
getDetails(u).then(function(data) {
console.log(data);
})