search

Home  >  Q&A  >  body text

Firebase GET request not returning data to client

We have an app with firestore database, using firebase cloud functions. We are trying to get data about each user from an external API. Our firebase cloud function is returning data - I can see it correctly in the logs. However, I don't see that data in the browser. I'm guessing maybe I'm not using async/await correctly?

Here's how we call the function from our application (in Vuex):

async retrieveByExternalId({ commit }, payload) {
      const retrieveByExternalId = await firebase.functions().httpsCallable('retrieveByExternalId')
      retrieveByExternalId({
        ID: payload
      })
      .then(result => {
        console.log(result.data)
        commit('setUserContractorPayProfile', result.data)
      })
    },

Result.data appears as null

Then, this is the cloud function:

exports.retrieveByExternalId = functions.https.onCall(async (data, context) => {
  const id = data.id
  
  axios({
    method: "GET",
    url: `https://website/api/v2/workers/external/${id}`,
    headers: {
      accept: '*',
      'Access-Control-Allow-Origin': '*',
      Authorization: 'API KEY'
    }
  })
  .then(response => {
    functions.logger.log("Response", " => ", response.data);
    return response.data
  })
  .catch((error) => {
    functions.logger.log("Error", " => ", error);
  })
});

In the function log I can see everything correctly.

Is this an async/await issue? Or am I returning wrong data?

Thanks!

P粉448130258P粉448130258258 days ago363

reply all(1)I'll reply

  • P粉696146205

    P粉6961462052024-03-21 07:00:09

    I haven't tried your code yet, but the problem is most likely due to you not returning the Promise chain in the cloud function .

    You should do this:

    return axios({ // <====== See return here
        // ...
      })
      .then(response => {
        functions.logger.log("Response", " => ", response.data);
        return response.data
      })
      .catch((error) => {
        functions.logger.log("Error", " => ", error);
      })

    Alternatively, since you declared the function async, use the await keyword like this:

    exports.retrieveByExternalId = functions.https.onCall(async (data, context) => {
    
        try {
            const id = data.id
    
            const axiosResponse = await axios({
                method: "GET",
                url: `https://website/api/v2/workers/external/${id}`,
                headers: {
                    accept: '*',
                    'Access-Control-Allow-Origin': '*',
                    Authorization: 'API KEY'
                }
            });
    
            functions.logger.log("Response", " => ", axiosResponse.data);
            return axiosResponse.data
        } catch (error) {
            // see https://firebase.google.com/docs/functions/callable#handle_errors
        }
        
    });

    reply
    0
  • Cancelreply