i want to fetch json data from openweathermap.org.but whenever i open my console it gives error(syntax error:JSON.parse() like this).and i am unable to find what's wrong with my code.plzz help thanks in advance.
<script>
console.log('about to fetch a rainbow');
async function catchRainbow() {
const response = await fetch('api.openweathermap.org/data/2.5/forecast/hourly?q=London,us&mode=xml&appid=e4386e3969c8d595d7f2f189cf2f786a');
const json= await response.json();
return json;
}
catchRainbow()
.then(json => {
console.log(json);
})
.catch(error => {
console.log('error!');
console.error(error);
});
</script>
You need to add the link prefix http:///https:// otherwise JS thinks you mean a local file.
console.log('about to fetch a rainbow');
async function catchRainbow() {
const response = await fetch('https://api.openweathermap.org/data/2.5/forecast/hourly?q=London,us&mode=xml&appid=e4386e3969c8d595d7f2f189cf2f786a');
const json = await response.json();
return json;
}
catchRainbow()
.then(json => {
console.log(json);
})
.catch(error => {
console.log('error!');
console.error(error);
});
Related
I'm new to all this export, import, async so please bare with me.
I have one file where I make API call and export that function so it can be used across other pages.
Of course on other page when function is invoked data payload is not yet there so i get undefind. So i tried to implement async (first time).
Please correct me if this is even possible or I I need some other method.
app.js:
export function inboxMeniIkona () {
//let req = xxxx
fetch(req)
.then(response => {
if (response.ok) {
return response.json()
} else {
throw new Error('NETWORK RESPONSE ERROR')
}
})
.then(data => {
return new Promise(resolve => {
return data // data here is allright
});
})
.catch(error => console.error('FETCH ERROR:', error))
}
And then I tried on other page:
import { inboxMeniIkona } from '~/app'
async function asyncCall() {
console.log('calling');
const result = await inboxMeniIkona();
console.log(result);
// expected output: "resolved"
}
asyncCall();
I'm still getting
CONSOLE LOG: calling
CONSOLE LOG: undefined
Please advise
Add async in your functions and await in your fecth and return it like this.
export async function inboxMeniIkona () {
//let req = xxxx
return await fetch(req)
.then(response => {
if (response.ok) {
return response.json()
} else {
throw new Error('NETWORK RESPONSE ERROR')
}
})
.then(data => {
return data // data here is allright
})
.catch(error => console.error('FETCH ERROR:', error))
}
I am having trouble finding the right query for Youtube API Docs for my problem as the documentation is quite large.
How can I display youtube videos for some specific category like Travelling or Technical with max 30 results also how can I get the results for searching a particular keyword
My initial code on Express.js :
app.get("/videos2", (req, res) => {
const url2 = "https://www.googleapis.com/youtube/v3/videos";
fetch(`${url2}&key=${process.env.GOOGLE_API_KEY}`)
.then((response) => {
return response.json();
})
.then((json) => {
res.json(json);
});
});
use
sync function getAllUrls(urls) {
try {
var data = await Promise.all(
urls.map((url) =>
fetch(url)
.then((response) => {
return response.json();
})
.then((json) => {
return json.items;
})
)
);
return data;
} catch (error) {
console.log(error);
throw error;
}
}
I have to make a fetch call at a url and after getting its response I want to use those results to call another fetch. I have following code:-
async function getDate(request) {
let data;
console.log('handle request called')
await fetch('<first-url>')
.then(res => {
let urls = res.json()
console.log('urls are ', urls)
return urls.data
})
.then((urls) => {
let url = urls[0]
console.log('url is ', url)
return fetch(url)
})
.then((res) => {
data = res.body
})
.catch(() => {
console.log("something went wrong")
})
return new Response(data, {
headers: { 'content-type': 'text/html' },
})
}
I followed the above method after following this tutorial. However it does not seem to work and I am getting urls are {Promise:[Pending]}.
Here issue with return res.json(). res.json() is promisable object, so u have to resolve it to get data.
For your example:
const fetch = require("node-fetch");
async function getDate() {
let data;
console.log("handle request called");
return await fetch('<first-url>')
.then((res) => res.json())
.then((urls) => {
console.log("urls are ", urls);
if (urls.length)
return Promise.all(urls.map((url) => fetch(url).then((x) => x.json())));
return [];
})
.then((responses) => {
console.log("urls are ", responses);
return responses;
});
}
getDate().then(console.log);
Sample:
async function getDate() {
let data;
console.log("handle request called");
return await fetch("https://api.covid19api.com/countries")
.then((res) => res.json())
.then((urls) => {
console.log("urls are ", urls);
return urls;
});
}
getDate().then(console.log);
I have this function that fetches a JSON object.
function dataFetch(){
const url = "http://www.quotzzy.co/api/quote?key=436587";
fetch(url).then(function(response) {
return response.text();
}).then(function(text) {
console.log('Request successful', text);
}).catch(function(error) {
log('Request failed', error)
});
};
How can I return the indices in the JSON object individually to use in HTML?
Like, my name (object.name) and my quote is (object.text) from this source (object.source).
Use json() on the response. It returns a promise for the object.
function dataFetch(){
const url = "http://www.quotzzy.co/api/quote?key=436587";
fetch(url)
.then(function(response) {
return response.json();
})
.then(function(json) {
console.log(json.author.name);
});
.catch(function(error) {
log('Request failed', error)
});
}
More idiomatic:
function dataFetch(){
const url = "http://www.quotzzy.co/api/quote?key=436587";
fetch(url)
.then(response => response.json())
.then(json => console.log(json.author.name, "said", json.text))
.catch(error => log('Request failed', error));
}
You can directly use the json() method of the Response object in this manner.
function dataFetch(){
const url = "http://www.quotzzy.co/api/quote?key=436587";
fetch(url)
.then(function(response) {
if(response.status == 200){
return response.json();
})
.then(function(responseObj) {
var text = responseObj.text;
var authorName = responseObj.author.name;
var source = responseObj.author.wiki;
...//access all attributes from the json
...//assign them to HTML elements
})
.catch(function(error) {
log('Request failed', error)
});
};
You can use response.json() to convert your response as JSON object. The response.json() method returns a promise. You will resolve promise you can get JSON object.
function dataFetch(){
const url = "http://www.quotzzy.co/api/quote?key=436587";
fetch(url)
.then(function(response) {
// return response.text(); // wrong
return response.json(); // right
})
.then(function(json) {
console.log('Request successful', json);
})
.catch(function(error) {
log('Request failed', error)
});
};
I got syntax error in my code.
async getJSON() {
await fetch(url)
.then((response) => response.text())
.then((responseText) => {
await AsyncStorage.setItem(STORAGE_KEY, responseText);
})
.catch((error) => {
console.warn(error);
});
},
Error is Unexpected token on await AsyncStorage.setItem(STORAGE_KEY, responseText);
I guess it's complaining await
For every await you need an async.
async getJSON() {
await fetch(url)
.then((response) => response.text())
.then(async (responseText) => { // <-- add async here
await AsyncStorage.setItem(STORAGE_KEY, responseText);
})
.catch((error) => {
console.warn(error);
});
},
Also... the point of async/await is to make the code look sync when is actually async. You can rewrite the above code like this:
async getJSON() {
try {
var response = await fetch(url);
var responseText = response.text();
await AsyncStorage.setItem(STORAGE_KEY, responseText);
} catch(error) {
console.warn(error);
}
}