NodeJS Axios response undefined on console.log API - javascript

I try to make this code work.
const axios = require('axios');
let bodyapi = axios.get('there's my api')
console.log(bodyapi.data) <- undefined
let body = bodyapi.data
console.log(body.discord) <- couldn't get parameter ''discord'' of undefined
Response type of the API:
"discord":{"Category":"activation","Qty":1542,"Price":1}
"vkontakte":{"Category":"activation","Qty":133,"Price":21}
I get it ''undefined''. Running on NodeJS.

axios return promise
const axios = require('axios');
// use async await
(async ()=>{
let bodyapi = await axios.get('there's my api')
console.log(bodyapi.data) // response
})()
// other way
axios.get('there's my api').then(data=> console.log(data))

You can chain a then method as axios returns promise.
you can also chain a catch method to catch potential errors.
const axios = require('axios');
axios.get('there's my api').then(bodyapi => {
console.log(bodyapi.data)
let body = bodyapi.data
console.log(body.discord)
}).catch(error => {
console.log(error);
});
hope this helps. GOOD LUCK :)

Axios Returns a promise. You can look at the documentation here
You can either use await to wait for the response in that case you should use a try catch block to make sure you take care of the errors from your discord Endpoint. This is a good read on error handling for asnyc/wait (here)
Like #arshpreet suggested
(async ()=>{
try{
let bodyapi = await axios.get('there's my api')
console.log(bodyapi.data) // response
} catch(error){
console.error(error)
}
})()
Or you can do it then and catch to take care of the errors.
just like waleed has mentioned.

Related

How can I send data on a get and receive a return?

I have to send this data in a get request but I don't know how to do it. Can you help me?
const ROUTE = "public/v1/route";
export async function showRoute(
flow: string,
token: string
): Promise<RouteParams> {
const response = await client.get(ROUTE);
return response.data;
}
You can use async/await or .then() promise chaining:
import {showRoute} from './path-to-showRoute'
showRoute(/* params */).then(data => sendGetRequest(data))
//or
async function sendRouteInfo(){
const routeData = await showRoute(/* params */)
if (routeData) sendGetRequest(routeData)
}
PS: sendGetRequest is a mock function which simply sends a get request using axios or fetch
axios.get(${URL})
.then(response => console.log(response.data)
.catch(err)=> console.log(err)
That is when you are using axios (npm i axios) then import it
I think what you're looking for is the Fetch-API. For example,
const ROUTE = resourcePath + '?' + new URLSearchParams({ ...params })
fetch(ROUTE) // sends a GET request
.then((res: Response) => res.json() as MyExpectedDataType) // parses JSON response content
.then((data: MyExpectedDataType) => {
// do something with data
})
.catch(err => {
})
// or
async function showRoute(): Promise<Something> {
try {
const res: Response = await fetch(ROUTE)
const data = await res.json() as MyExpectedDataType
// do something with data
}
catch (err) {
}
}
fetch returns a Promise type on which you can chain asynchronous callbacks using .then and handle errors with .catch and .finally. You can also pass request method, headers, body content etc. as an optional second argument to fetch, see the documentation.

How to assign the output of a Fetch call to a variable (JavaScript)

I try to connect the output of a Fetch call to my page variable, but I just cannot seem to do it.
Could you please check out the code underneath and help me out?
enter image description here
I think the async/await approach will solve your issues.
async outputvariable() {
try {
const response = await fetch('https://api2.online-conve', {
method: 'GET',
credentials: 'same-origin'
});
const rlt = await response.json();
return rlt;
} catch (error) {
console.error(error);
}
}
You will have to make the surrounding function an async function, and then await the response.
async function(){
try{
var outputVariable = await fetch("URL").text();
// Use outputVariable
} catch(e){
console.log('error', e);
}
}
Or you can use the axios instead of the fetch.
import axios from 'axios';
const response = await axios('https://api2.online');
console.log(response.data);

Axios get function returns a promise in React

I tried fetching data from a giphy api using the following function and print the returned value to the browser console.
const fetchData = (url) =>
{
return axios.get(url).then(res => res.data.data);
}
const data = fetchData(giphy_url);
console.log(`Data: ${data}`);
But on printing the value of the data variable, it prints:
Data: [object Promise]
I want the data in the response to be accessed.
Is there something that I am missing?
Axios API calls return a Promise object. From Axios documentation, "Axios is a promise-based HTTP Client for node.js and the browser."
You would need to await on a promise object to access the response value. Note that in order to use await keyword in your function, you would need to mark it as async. Do something like below.
const fetchData = async(url) =>
{
return await axios.get(url).then(res => res.data.data);
}
const data = fetchData(giphy_url);
console.log(`Data: ${data}`);
It happend because javascript is a non blocking language and axios' get function is a promise function. So when you print your data variable which is not fill yet, you should use it like this.
const fetchData = async (url) =>
{
return axios.get(url).then(res => res.data.data);
}
// careful that when you want to use await it should be on async function
const data = await fetchData(giphy_url);
console.log(`Data: ${data}`);
// or
fetchData(giphy_url).then((data)=>{
console.log(`Data: ${data}`);
})
You can use async/await to get data:
const yourFunction = async () => {
const data = await fetchData(giphy_url);
console.log(`Data: ${data}`);
}
I think you are handling axios in wrong way
const fetchData = async (url) =>{
return await axios.get(url);
}
const data = fetchData(giphy_url);
console.log(`Data: ${data}`)
Use async-await concept as below:
const fetchData = (url) => {
return axios.get(url);
}
const getData = async () => {
const data = await fetchData(giphy_url);
console.log(`Data: ${data}`);
}
getData();

Why doesn't the catch in async await code fire?

is there any .catch() method like there is with Promises for async await style of code?
Here's an example of a code written via Promise:
const apiURL = 'https://jsonplaceholder.typicode.com/todos/1';
const badURL = 'zhttps://wcaf.fajfkajf.gg'
function getData(url){
fetch(url)
.then(response => response.json())
.then(json => console.log(json))
.catch( err => console.log('cannot load api'))
}
getData(apiURL);
getData(badURL);
A simple function to try to load data and if not, display a basic error message. Now I was trying to transcribe this into async/await style code, issue was, I could not really figure out a way to write this with catch()
My best guess was to try try - catch but the catch part doesn't work:
const apiURL = 'https://jsonplaceholder.typicode.com/todos/1';
const badURL = 'zhttps://wcaf.fajfkajf.gg'
async function getData(url){
const response = await fetch(url);
try {
const json = await response.json();
console.log(json);
} catch (e) {
console.log('cannot load api');
}
}
getData(apiURL);
getData(badURL);
This loads the object API just fine, but never seems to go into the catch{} block despite being passed incorrect url.
Any idea what am I doing wrong?
As pointed out in the comments by #l-portet, this is because the code inside try { } block does not actually fail!
.json() will return a promise, regardless of the content of the parsed body text, so even though the initial fetch() fails, you can still call .json() on it - albeit it's completely redundant as it won't return anything meaningful.
Putting the fetch() request inside the try { } block does result in the expected behaviour:
const apiURL = 'https://jsonplaceholder.typicode.com/todos/1';
const badURL = 'zhttps://wcaf.fajfkajf.gg'
async function getData(url){
try {
const response = await fetch(url);
const json = await response.json();
console.log(json);
} catch (e) {
console.log('cannot load api');
}
}
getData(apiURL);
getData(badURL);
One thing you should be aware is that when an async function is executed, it always returns a promise, regardless the exit condition of the function.
If the function has an explicit return (or completes without crashing) the promise will be resolved to the value it returned (or to undefined if there was no explicit return), if the function throws, the promise will be rejected, passing the thrown error object.
Knowing that you could simply handle the error where you use the function, for example:
const apiURL = 'https://jsonplaceholder.typicode.com/todos/1';
const badURL = 'zhttps://wcaf.fajfkajf.gg'
async function getData(url){
const response = await fetch(url);
return await response.json();
}
getData(apiURL).then(data => console.log(data));
getData(badURL).catch(err => console.log('error:', err));
IMHO handling the error closely where you have a use-case of the function makes more sense, since normally when you expect to have an error is because we have a way to handle it (maybe try another API url in this example).
One pattern that I've been using lately is to wrap promises in a way they resolve returning a tuple, in the convention of [error, value] (similar to the way the Go programming language handle async error), in that way for instance you could handle the error in the specific getData call, for example:
const apiURL = 'https://jsonplaceholder.typicode.com/todos/1';
const badURL = 'zhttps://wcaf.fajfkajf.gg'
async function getData(url){
const response = await fetch(url);
return await response.json();
}
// simple utility function
const safePromise = promise =>
promise.then(data => [null, data]).catch(err => [err, undefined]);
(async () => {
const [err, json] = await safePromise(getData(apiURL))
if (err) {
// handle the error
}
console.log(json)
const [error, data] = await safePromise(getData(badURL))
if (error) {
console.log('Error:', error);
}
})()
Check the following library which basically ships this pattern:
await-to-js

Node JS Asyncrounous Function Doesn't Return the Right Result

Have this module.exports file which returns a function to fetch some profiles using the gender parameter as the body of the request.
Here, the function is asynchronous and waits for the fetch to return a result so it can proceed. I am using all the async js rules but still, it returns undefined.
I know that there isn't any problem in the URL or the API endpoint because I directly console logged it in .then() the promise returned by the fetch, it firstly consoles logs undefined and then it returns the original value.
Here's the code:
// Pre Configuration
const fetch = require('node-fetch')
module.exports = async (req, res, genderCode) => {
const apiURL = req.apiURL
const requestURL = `${apiURL}/featured?gender=${genderCode}`
await fetch(requestURL)
.then(res => res.json())
.then(data => {
return data._embedded.compactProfiles
})
}
Also where I call the function, I also use await there.
Can anybody tell what's wrong with it?
You haven't put a return statement in the anonymous function you export.
You await the value from the second then statement (although I'm at a loss as to why you are using then and async/await), and then do nothing with it.
module.exports = async (req, res, genderCode) => {
const apiURL = req.apiURL
const requestURL = `${apiURL}/featured?gender=${genderCode}`
const res = await fetch(requestURL);
const data = await res.json();
return data._embedded.compactProfiles
}

Categories

Resources