Skip to content

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() {
        .then(function (response) {
            // I need this data here ^^
        .catch(function (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.


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) =>

    // return it
    return dataPromise

// now we can use that data from the outside!
    .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 =>

Or with async/await:

async function axiosTest() {
    const response = await axios.get(url)