Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning data from Axios API

I am trying to use a Node.JS application to make and receive API requests. It does a get request to another server using Axios with data it receives from an API call it receives. The second snippet is when the script returns the data from the call in. It will actually take it and write to the console, but it won't send it back in the second API.

function axiosTest() {     axios.get(url)         .then(function (response) {             console.log(response.data);             // I need this data here ^^             return response.data;         })         .catch(function (error) {             console.log(error);         }); } 

...

axiosTestResult = axiosTest();  response.json({message: "Request received!", data: axiosTestResult}); 

I'm aware this is wrong, I'm just trying to find a way to make it work. The only way I can seem to get data out of it is through console.log, which isn't helpful in my situation.

like image 334
bunkerguy Avatar asked Feb 26 '18 01:02

bunkerguy


People also ask

How do I return data from Axios?

To return data from axios API with JavaScript, we can use the return statement. const axiosTest = async () => { const response = await axios. get(url); return response. data; };

How do I get data from Axios post?

A POST request can be made using Axios to “post” data to an endpoint. This endpoint may then use this POST request to perform a certain task or trigger an event. The HTTP post request is performed by calling axios.

What type of data does Axios get return?

The Axios response object consists of: data - the payload returned from the server. status - the HTTP code returned from the server. statusText - the HTTP status message returned by the server.


1 Answers

The issue is that the original axiosTest() function isn't returning the promise. Here's an extended explanation for clarity:

function axiosTest() {     // create a promise for the axios request     const promise = axios.get(url)      // using .then, create a new promise which extracts the data     const dataPromise = promise.then((response) => response.data)      // return it     return dataPromise }  // now we can use that data from the outside! axiosTest()     .then(data => {         response.json({ message: 'Request received!', data })     })     .catch(err => console.log(err)) 

The function can be written more succinctly:

function axiosTest() {     return axios.get(url).then(response => response.data) } 

Or with async/await:

async function axiosTest() {     const response = await axios.get(url)     return response.data } 
  • Guide on using promises
  • Info on async functions
like image 141
kingdaro Avatar answered Sep 18 '22 10:09

kingdaro