Cannot retrieve specific JSON data from API call [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
I am trying to use the variable 'myResult' to return specific JSON data. I believe I may have written the 'myResult' variable wrong and I am not querying for the correct data. The path for '[1].show.score'is correct and I will add in screenshots of the JSON data I am trying to call.
When I call for this data, I get returned to me this error:
[![My error][2]][2]
Here is the result of 'url'
[![The returned JSON data from the variable 'url'][1]][1]
Here is my code:
document.querySelector('.myButton').addEventListener('click', function(){
var query = document.getElementById('main').value;
var url = fetch("http://api.tvmaze.com/search/shows?q="+query)
.then(response => response.json())
.then(data => console.log(data));
var myResult = url[1].show.score;
console.log(myResult);
})```
[1]: https://i.stack.imgur.com/lTn8V.png
[2]: https://i.stack.imgur.com/kS7gB.png

You cannot access the data from url the way you are trying to access it with url[1].show.score because url is a promise that you can call .then() and .catch() on, which you already do in order to receive the data.
If you want myResult to use the specific data, you need to use it within the .then() callback
So you may have something like this in the end:
document.querySelector('.myButton').addEventListener('click', function(){
var query = document.getElementById('main').value;
fetch("http://api.tvmaze.com/search/shows?q="+query)
.then(response => response.json())
.then(data => {
console.log(data));
var myResult = data[1].show.score;
console.log(myResult);
}
})

Related

Javascript fetch POST call doesn't wait for resolve [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 1 year ago.
I am working on a Python dashboard with FastAPI and Javascript. I have created a POST call returning an URL in FastAPI, which I am trying to fetch with Javascript and pass to the player. The output of this POST call is JSON. I am trying to assign the value of a certain key to the laURL variable. The problem is that even though I am using await and async function, Javascript is not really waiting for resolving the response and the second function is executed before the completion of the laURL assignment.
async function fetchLicense(playbackURL) {
try {
let response = await fetch(apiURL, {
method: "POST"
});
if (response.ok) {
let result = await response.json();
let laURL = JSON.parse(result).la_url;
return await laURL;
} else {
console.log("POST Error: ", response);
}
} catch (error){
console.log("POST Error: ", error);
}
}
And then I am using the returned value in another function:
function fetchSource(playbackURL) {
let laURL = fetchLicense(playbackURL);
const source = {
dash: playbackURL,
drm: {
widevine: {
LA_URL: laURL
},
immediateLicenseRequest: true
}
};
return source;
I have checked and tried a couple of different solutions, but nothing seems to be working.
This should be really something straightforward, but unfortunately, the solution isn't so obvious to me.
Javascript async/await is just syntactic sugar for using Promises. fetchLicense hence returns a promise. You can use Promise.then(/* callback */) to specify what should happen when data is resolved.
If you're unfamiliar with this, the following link might help you understand how it works exactly: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

Data is not pushed in an array [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 1 year ago.
I got data from API and tried to push it in an array, but when I print it, it's empty. The data is JSON.
fetch("url")
.then((response) => response.json())
.then((data) => sohawnID.push(data.id))
console.log(sohawnID)
//output: []```
this is because synchronous behavior of node js. what you need is to put you api call method inside a Promise function and then call it using async await. By this way program 1st wait for api response and then push data to your array
The reason it prints empty is console.log(sohawnID) called before the promise fulfil meaning you are trying to print result before it arrives. You can do this:
fetch("url")
.then((response) => response.json())
.then((data) => {
sohawnID.push(data.id);
console.log(sohawnID)
})
``

Website does a POST Request, how can I get the result of that request with JS? [duplicate]

This question already has answers here:
Intercept a certain request and get its response (puppeteer)
(2 answers)
Closed 1 year ago.
So I am not trying to bypass anything I just need to get the value returned by the request.
Example:
I go to a website.
Click a button.
Fill a RECAPTCHA
Once RECAPTCHA has been filled & verified it sends a request to an API with a payload & then the response returns a few values such as:
{"success":true,"data":{"signature":"SIG_K1_xxxxfp3w4EdhcCYqHwTntM19G7w4NCDt6ruTPistKPRow47cyeUiRMsc5YN9JMkqjtrfsk2Pf3nZkDY54rNWS5cyDhtE21y","nonce":1734981752}}
So I need to SOMEHOW grab the value of "signature" and "nonce" and again, I remind you, I AM NOT the one doing the FETCH request, the website/captcha is as soon as the captcha is validated. Is there anyway to do this?
PS: Before someone suggest that I do the FETCH request myself, I can't because it passes a "challenge" parameter in the payload which is unique to each RECAPTCHA and there's no way to find out its value.
You need to write an interceptor for this. The basic idea is that you take the function, that RECAPTCHA uses (which is either fetch or XMLHttpRequest), make a copy of the original, and write an interceptor that contains whatever you want to do with the data plus the original function.
For fetch something like this:
const originalFetch = window.fetch;
window.fetch = function() {
return originalFetch.apply(this, arguments)
.then((res) => {
res
.clone()
.json()
.then(data => {
console.log("fetch", data);
})
.catch(err => console.error(err));
return res;
});
}
For XMLHttpRequest:
const origOpen = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function() {
this.addEventListener('load', function() {
console.log("open", JSON.parse(this.responseText))
});
origOpen.apply(this, arguments);
};
const origSend = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.send = function(data) {
this.addEventListener('load', function() {
console.log("send", data);
});
origSend.apply(this, arguments);
};

Fetch API returning "undefined" [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
I am currently learning how to work with APIs, and I am having a little trouble with fetching the data from an API. The code below successfully gets a response but does not actually get any data from the server. How do I go about solving this?
const onClick = () => {
fetch(
`https://collectionapi.metmuseum.org/public/collection/v1/objects/45734`
)
.then(res => {
if (res.ok) {
console.log(res)
console.log('SUCESSS')
} else {
console.log("Not Successful")
}
})
.then(data => {
if (data) {
console.log(data)
} else {
console.log("undefined data")
}
})
.catch(error => console.log('ERROR'))
console.log(results);
}
The promise .then methods can be chained in a way each chained then methods will receive the returned value of the previous one. In your case, the first one does not return any values, making the second one receiving nothing, also well known as undefined.
As the url your code is calling return json content, you should return after loging success the result of res.json().
This will read the stream of the response body and parse it as json, using a promise.

fetch function return Promise <pending> [duplicate]

This question already has answers here:
Why does .json() return a promise?
(6 answers)
Closed 11 months ago.
So my code here return a Promise and since I'm using then syntax I don't know why that happens :-??
fetch('someurltoAJsonFile.json')
.then(function(response) {
console.log(response.json());});
response.json() in node-fetch library also returns a promise, instead try
fetch('someurltoAJsonFile.json')
.then(response => response.json())
.then(data => {
console.log(data)
});
you can look up more details about it here
EDIT:
It seems that the returned response wasn't in the valid json, so for the sake of completeness here is a code for text
fetch('someurltoAJsonFile.json')
.then(response => response.text())
.then(data => {
console.log(data)
});
The function given as then parameter will be executed asynchronously (sometime in the future when your server returns a response), but then itself return Promise immediately (in synchronous way) by its definition
If you want to code looks less nested (more as synchronous code) you can use await but you must opaque whole code with async function
async function load()
{
let response = await fetch('someurltoAJsonFile.json');
let data = await response.json();
console.log(data);
}
Debating whether or not this qualifies as an answer, but I ran into a similar situation today that led me to this question even though my problem ended up being environment related.
If you are seeing promise pending and your code is correct and you spend way too much time trying to figure out why the console.log isn't showing, double check that you have "Info" turned on in chrome's dev tools. I only had warnings turned on so I wasn't seeing my console.log.
This code works and show a good way to make a fetch and get the promise without the pending problem.
Run this code in your server if you have cors problem download this extension in google chrome "Allow CORS: Access-Control-Allow-Origin"
async function invoices()
{
let response = await fetch('https://blockchain.info/latestblock?utm_medium=referral&utm_campaign=ZEEF&utm_source=https%3A%2F%2Fjson-datasets.zeef.com%2Fjdorfman');
let data = await response.json();
console.log(data);
return data;
}
invoices().then(data => {
console.log(data);
});

Categories

Resources