No response returned from fetch - javascript

I am trying to get data from the API and it doesnot return any value. I have tried to put the apiUrl in the browser directly it works there. Even a get request via postman returns request.
fetch(apiUrl)
.then((response) => {
let data = JSON.parse(response)
console.log(data)
return data;
})
Also in Chrome debugger, there is no request in the network tab as well. I have used the same code earlier to get the response.

Calling the API with Fetch gives a promise, and converting it to JSON will return yet another promise, which you need to "await" for again. This is how it should look like
fetch(URL)
.then(response => response.json())
.then(json => console.log(json))

fetch(apiUrl)
.then((response) => {
return response.json().then( res => {
let data = res;
console.log(data)
return data;
})
})
try this

Related

Javascript Fetch Function returns [object Promise]

I'm currently working on a project, which includes a website, built and run by Django. On this website, I'm trying to load data through fast API and try to load this data through JavaScript and the Fetch API. But I always get instead of the Data provided through the API, an [object Promise]. I've tried many different methods but none seem to work.
I've tried for example:
document.getElementById("1.1").innerHTML = fetch('the URL')
.then(response => response.text())
or
document.getElementById("1.1").innerHTML = fetch('the URL')
.then(response => response.text())
.then((response) => {
console.log(response)
})
and many other methods. I've also checked and the API request works perfectly, returning a string.
You want the setting of the html to appear when you log the final response, eg:
fetch('the URL')
.then(response => response.text())
.then((response) => {
console.log(response)
document.getElementById("1.1").innerHTML = response
})
Other ways including making the whole of the response promise to be fulfilled:
const getData = async (url) => {
const res = await fetch(url)
const resText = await res.text()
return resText
}
const addTextFromUrl = async (url, element) => {
const text = await getData(url)
element.innerHtml = text
}
addTextFromUrl('theUrl', document.getElementById("1.1"))
Generally it is a little easier to follow the async/await syntax when learning, but you should always try/catch any errors.
Every .then call does return a new promise. So
You need to assign value in a callback or use async/await
fetch('the URL')
.then(response => response.text())
.then((response) => {
document.getElementById("1.1").innerHTML = response
})
or do it inside an async function
async function getHtml() {
document.getElementById("1.1").innerHTML = await fetch('the URL')
.then(response => response.text())
}
getHtml();
W/o using then
async function getHtml() {
const response = await fetch('the URL');
const html - await response.text();
document.getElementById("1.1").innerHTML = html;
}
getHtml();

Not getitng the same response in postman and fetch

I have this function to make a request to gyphy api
const getGifs = async () => {
const url = 'https://api.giphy.com/v1/gifs/search?api_key=mykey&q=ps5&limit=5';
const resp = await fetch(url)
.then(response => console.log(response));
}
In postman I get a json with the searched data but in javascript I get a response object, how can I get the searched data?
The fetch API does not return the raw response a such. The object you're getting is one that can be transformed into what you need. Since you're expecting JSON data, then your code should be:
const getGifs = async () => {
const url = 'https://api.giphy.com/v1/gifs/search?api_key=mykey&q=ps5&limit=5';
const resp = await fetch(url)
.then(response => response.json())
.then(jsonData => console.log(jsonData)) // the response you're expecting
}
The .json() method returns a Promise that resolves with your JSON parsed data.
According to the giphy api doc, the search endpoint returns a data element, which is an array of gifs. Just inspect your response object and see if it has a data element, then log response.data, not the full response
.then(response => console.log(response.data));
you are returning undefined because you are returning console.log() which is not right. Change it to response.body()
const fetch = require("node-fetch")
const getGifs = () => {
const url = 'https://api.giphy.com/v1/gifs/search?api_key=mykey&q=ps5&limit=5';
const resp =fetch(url)
.then(response => response.data);
return resp;
}
console.log(getGifs());

Display a response from a Fetch with HTML?

My goal is to display some data on a webpage that I have obtained with a Fetch using HTML.
My Fetch (which works) looks like this
<script>
let response = fetch(
"https://api.seatgeek.com/2/events?per_page=100&venue.city=boston&client_id=MYAPIKEY"
)
.then((response) => response.json())
.then((response) => console.log(response.events[0].title));
</script>
The code works and logs a response to the console as I've requested. Now, I'd like to show some of the response on my webpage.
My attempts have looked something like this
<center><h2 id="response"></h2></center>
<script>
let response = fetch(
"https://api.seatgeek.com/2/events?per_page=100&venue.city=boston&client_id=MYAPIKEY"
)
.then((response) => response.json())
.then((response) => console.log(response.events[0].title))
.then((response) => {
document.getElementById("response").innerHTML = response.events[0].title;
});
</script>
Context and details:
I've done some mobile dev, but I'm a noob with even basic HTML/JS interaction on web so there are some holes in my knowledge here
I'll be implementing this code injection as a code block on a Squarespace (Adirondack template, Adirondack family) but I don't think the Squarespace context should matter (the Fetch works just fine, and the code injection has been displaying other things just fine)
Error from my attempt: VM22305 about:srcdoc:8 Uncaught (in promise) TypeError: Cannot read property 'events' of undefined
I'm not committed to any particular way of displaying, I'm just trying to get the ball rolling by seeing something on the page
Thanks for your help!
Your second then is console logging and returning nothing (console.log returns undefined), so in the next then statement the response is undefined.
Change your code to:
<center><h2 id="response"></h2></center>
<script>
let response = fetch(
"https://api.seatgeek.com/2/events?per_page=100&venue.city=boston&client_id=MYAPIKEY"
)
.then((response) => response.json())
.then((response) => {
console.log(response.events[0].title);
return response;
})
.then((response) => {
document.getElementById("response").innerHTML = response.events[0].title;
});
</script>
And it should work.
If you want a chain of thens, you need to return a promise to the next one, like this:
let response = fetch(
"https://api.seatgeek.com/2/events?per_page=100&venue.city=boston&client_id=MYAPIKEY"
)
.then((response) => response.json())
.then((response) => {
document.getElementById("response").innerHTML = response.events[0].title;
});

Fetching API and return Specific data

So, I am trying to fetch API from Calendarific I fetch it and I get data in console here is the code below:
btn.addEventListener('click', function fetchApi(){
fetch('https://calendarific.com/api/v2/holidays?&api_key=<myKey>&country=US&year=2019')
.then(res => res.text())
.then(data => {
//holiday.innerHTML = data;
//console.log(data);
console.log(data.holidays[0].name)
})
.catch(err => console.log(err));
// alert('click')
});
But I want to access specific data like. I want to access only the name and how can I do that? Code works fine but I faced problem to access specific data from API I tried holidays[0].name But it shows undefined What I am doing wrong here?
When receiving JSON, instead of
.then(res => res.text())
.then(...
use
.then(res => res.json())
.then(...
Also, according to calendarific documentation, there's a response key you should query first:
console.log(data.response.holidays[0].name)

Fetch res.json() Attempt to invoke intergace method 'java.lang.String...'

I'm trying to convert a response from fetch function into json format but when I do so I get an error Attempt to invoke interface method 'java.lang.string com.facebook.react.bridge.ReadableMap.getString(java.lang.String)' on a null object reference.
Here is my code snippet with fetch function:
export const fetchAllUsers = () => {
fetch('http://192.168.1.103:3000/api/userData')
.then(res => {
res.json();
//console.warn('res keys = ' + Object.keys(res))
})
}
If comment back the row with console.warn I see the following "res keys = type, status, ok, statusText, headers, url, _bodyInit, _bodyBlod, bodyUsed".
bodyUsed = false
status = 200
type = default
Why I can't convert a response into json format? Or is there any another way to do so?
UPDATE
I've added the second then but I still get the error and the console.warn('res is json') is not running:
export const fetchAllUsers = () => {
fetch('http://192.168.1.103:3000/api/userData')
.then(res => {
res.json();
//console.warn('res keys = ' + Object.keys(res));
})
.then(res => {
console.warn('res is json');
console.warn(res);
})
}
UPDATE_2
I've run fetch function with another url but still got the problem. It seems like .json() causes the error. When I'm trying to console the result of fetch in the first .then() I get json object with type, status etc keys.
export const fetchAllUsers = () => {
fetch(`http://${localIP}:${port}/api/userData`)
//.then(res => res.json())
.then(json => console.warn('JSON: ' + json))
.catch(e => console.warn('ERROR: ' + e))
}
UPDATE_3
Forgot to mention that I'm creating an Android app with React Native. For testing I'm using a physical smartphone. Chrome version there is 73.0.3683.
I've replaced my fetch query with the following:
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => console.log(json));
But still get the same error.
When I run it in https://jsfiddle.net/ it works. So the reason is hidden inside the code execution on a smartphone.
There must be more context to your problem; see the below snippet. This clearly works.
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => console.log(json));

Categories

Resources