I have used the shrtcode api and I dont know how to store its data.
var requestOptions = {
method: 'GET',
redirect: 'follow'
};
fetch("https://api.shrtco.de/v2/shorten?url=www.google.com", requestOptions)//api
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
}
Response
ok true
result
code "fQdPc"
short_link "shrtco.de/fQdPc"
full_short_link "https://shrtco.de/fQdPc"
short_link2 "9qr.de/fQdPc"
full_short_link2 "https://9qr.de/fQdPc"
short_link3 "shiny.link/fQdPc"
full_short_link3 "https://shiny.link/fQdPc"
share_link "shrtco.de/share/fQdPc"
full_share_link "https://shrtco.de/share/fQdPc"
original_link "http://www.google.com"
How can I print or store the value of "full_short_link "?
Like this?
const doStuff = async () => {
try {
const res = await fetch('https://api.shrtco.de/v2/shorten?url=www.google.com');
const json = await res.json();
console.log('full_short_link', json.result.full_short_link);
} catch (err) {
console.error(err);
}
};
doStuff();
Related
I am trying to get pub locations data from MYSQL server and my fetch function works well. But after that, this try-catch block does not return anything. I also tried without try-catch block but it does not change anything
getPubsFromDatabase = async () => {
let response = await fetch(fetchDataUrl, {
method: 'POST',
headers:
{
'Accept': 'application/json',
'Content-Type': 'application/json',
},
});
try{
let json = await response.json();
console.log(json)
return json;
}
catch (error) {
console.log(error);
}
}
And here, I am trying to get the return value of the function. But in this version, I cannot even see any console.log output. What I mean by the version is, if I put 2nd line out of the async block without "await" keyword, I can see the console.log but I it gives "undefined" then.
(async () => {
const locationsData = await getPubsFromDatabase();
console.log(locationsData)
})()
You can use then and catch in the function fetch.
const getPubsFromDatabase = () => {
return fetch(fetchDataUrl, {
method: 'POST',
headers:
{
'Accept': 'application/json',
'Content-Type': 'application/json',
},
}).then(async (response) => {
const json = await response.json().then((data)=>{
return data;
}).catch((err)=>{
console.log('error from json method: ',err);
return { error: {
message: 'error from json method',
object: err
}};
});
console.log(json);
return json;
}).catch((error) => {
console.log('error from request: ', error);
return {
error: {
message: 'error from request', object: error
}
};
});
}
And when you use the method getPubsFromDatabase would be of the next way:
(async () => {
const locationsData = await getPubsFromDatabase();
console.log(locationsData);
})()
You can use Promise to return either result or error, In the example given below i have used axios library but you can also try same with fetch api
For Example
export const getData = () => {
return new Promise((resolve, reject) => {
const url = ApiConstant.BASE_URL + ApiConstant.ENDPOINT;
const API_HEADER = {
"Authorization": token,
};
axios
.get(url, {
headers: API_HEADER,
})
.then((res) => {
resolve(res.data);
})
.catch((error) => {
// handle error
reject(error);
console.log(error);
});
})
}
You can call the above function in component or screen like this:
getData().then(
(data) => {
}
).catch(
error => {
console.log(error)
}
)
I solved the problem by instead of returning the value from the function, I set the value inside the function. This seems to work now.
const [locationsData, setLocationsData] = useState();
getPubsFromDatabase = async () => {
let response = await fetch(fetchDataUrl, {
method: 'POST',
headers:
{
'Accept': 'application/json',
'Content-Type': 'application/json',
},
});
try{
let json = await response.json();
setLocationsData(json); // Here, I changed the value of the locationsData instead of returning
}
catch (error) {
console.log(error);
}
}
And to call the function:
useEffect(()=> {
getPubsFromDatabase();
},[])
The below code always return the below wired object
{"_U": 0, "_V": 0, "_W": null, "_X": null}
as response.
Here is my code
getData = () => {
fetch('http://192.168.64.1:3000/getAll',{
method: 'GET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
}
})
.then((response) => {
console.log('Response:')
console.log(response.json())
console.info('=================================')
})
.catch(err => console.error(err));
}
componentDidMount(){
this.getData();
}
I am using node, express, Mysql as backend and react-native frontend
my backend code is here
app.get('/getAll',(req,res) => {
console.log('getAll method Called');
con.query('select * from dummy',(err,results,fields) => {
if(err) throw err;
console.log('Response');
console.log(results);
res.send(results);
});
});
The above code gives correct output in console but fetch API is not.
i cant find solution for the my problem. Thanks in advance.
That indicates that you are logging the promise before it resolves - the result of when you:
console.log(response.json())
How do I access promise callback value outside of the function?
As #Evert rightfully pointed out in comments, this is because response.json() returns a promise object.
So, you'll need to chain an additional .then() after you call response.json() where you log the resolved promise.
getData = () => {
fetch('http://192.168.64.1:3000/getAll',{
method: 'GET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(err => console.error(err));
}
Add async and await to your code:
getData = async () => {
await fetch('http://192.168.64.1:3000/getAll',{
method: 'GET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
}
})
.then((response) => {
console.log('Response:')
console.log(response.json())
console.info('=================================')
})
.catch(err => console.error(err));
}
So the issue is that you are not waiting for your Promise to resolve and this can be solved easily.
try {
const res = await fetch(
'your_api',
);
const data = await res.json();
} catch (error) {
console.log(error);
}
So the issue is that you are not waiting for your Promise to resolve. Have added await and that'll go next line once the await action is completed.
const user_fun = async (userId) => {
const response = await fetch("url");
const data = await response.json();
console.log("users ", data);
return data;
};
let data = user_fun();
console.log("users ", data);
const test = order.restaurantId;
console.log(test); //here test == 3
const getAvailableHours = async () =>{
console.log(test); //test == undefined
await fetch(`API Address`, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
})
.then(response => {
return response.json();
})
.then(responseText => {
console.log(responseText);
})
.catch(error => {
console.log(error);
});
}
Hi, I am trying to fetch data from API by using restaurant ID but when I'm passing the ID to async it becomes undefined.
I am new in React.js, anyone has any ideas?
async await syntax allows you to avoid .then method, so you can handle promises with a more readable syntax. With try catch blocks you can handle errors, try this:
const getAvailableHours = async () => {
try {
let response = await fetch('https://api-address-goes-here/', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
let responseText = await response.json();
return responseText;
} catch (err) {
console.log(err)
}
}
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'm trying to return some json data using the res.json() function from Express, but instead of returning a new json object each time it seems that it's appending to the old json object each time. This means that I'm receiving duplicate data in the same response object.
My code looks like this:
await Promise.all(promises)
.then(responses => res.json(responses))
.catch(error => console.error(error))
Returned data example:
[
[data]
]
Second request returned data sample:
[
[data],
[data(1)]
]
My code returns a list of responses which I want, but on repeated requests to the same function the new response is appended to the data from the old response and sent back. Is this intended? Am I doing something wrong?
edit: here is the rest of my code for context. I'm new to js and async programming so let me know if something I'm doing is terribly wrong.
const fetch = require('node-fetch')
const authFunctions = require('./auth')
var bearer_token
const space_id = 11111
let id_promises = []
async function get_category_rooms(category_id)
{
return fetch(`https://url.com/api/${category_id}`,
{
headers:
{
'Authorization': `Bearer ${bearer_token}`
}
}).then(response => response.json())
.then(data => data.map(category => category.items))
.catch(err => console.error(err))
}
async function get_category_ids() {
return fetch(`https://url.com/api/${space_id}`,
{
headers:
{
'Authorization': `Bearer ${bearer_token}`
}
})
.then(response => response.json())
.then(data =>
{
categories = data[0]["categories"].filter(category => category.name !== "category i don't want")
categories.forEach(category_item =>
{
id_promises.push(new Promise((resolve, reject) =>
{
resolve(get_category_rooms(category_item.cid))
}))
})
})
}
async function get_room_bookings(room_id) {
return fetch(`https://url.com/api/${room_id}`,
{
headers:
{
'Authorization': `Bearer ${bearer_token}`
}
})
.then(response => response.json())
.then(data => data)
}
async function get_not_group_room_reservations(req,res)
{
let room_promises = []
if (!await authFunctions.auth_check(bearer_token))
{
console.log('invalid bearer token. changing bearer')
bearer_token = await authFunctions.auth()
}
await get_category_ids()
let rooms = await Promise.all(id_promises)
.then(responses =>
{
let room_ids = responses.flat(2)
room_ids.forEach(room_id =>
{
room_promises.push(new Promise((resolve, reject) =>
{
resolve(get_room_bookings(room_id))
}))
})
})
.catch(error => console.error(error))
await Promise.all(room_promises)
.then(responses => res.json(responses))
.catch(error => console.error(error))
}