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.
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; };
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.
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.
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With