Firebase GET request not returning data to client
P粉448130258
P粉448130258 2024-03-20 08:18:04
0
1
326

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粉448130258
P粉448130258

reply all(1)
P粉696146205

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
    }
    
});
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!