How to correctly execute a axios POST request within a firebase cloud function

与世无争的帅哥 提交于 2021-01-25 05:25:09

问题


I'm currently working on an app that publishes a post to facebook on call of the below firebase cloud function. Problem now is that the request throws back an error 408:

Error - Post on Facebook { Error: Request failed with status code 408
at createError (/user_code/node_modules/axios/lib/core/createError.js:16:15)
at settle (/user_code/node_modules/axios/lib/core/settle.js:18:12)
at IncomingMessage.handleStreamEnd 
(/user_code/node_modules/axios/lib/adapters/http.js:201:11)
at emitNone (events.js:91:20)
at IncomingMessage.emit (events.js:185:7)
at endReadableNT (_stream_readable.js:978:12)
at _combinedTickCallback (internal/process/next_tick.js:80:11)
at process._tickDomainCallback (internal/process/next_tick.js:128:9)

The buzzling thing for me is that the same request via postman succeeds without any issues :( Maybe one of you guys knows a fix for this problem :)

const functions = require('firebase-functions');
const cors = require('cors')({ origin: true });
const admin = require('firebase-admin');
const db = admin.firestore();
const axios = require('axios');

export const facebook = functions.region('europe- 
west1').https.onRequest((req, res) => {
  return cors(req, res, () => {

    // Post data
    const data = {
      scheduled: null,
      message: '',
      accessToken: 'token'
    }

    // Get Post data through ID
    db.collection("articles").doc(req.body.id)
    .get().then((doc) => {
      if (doc.exists) {
          data.message = doc.data().meta.facebook.description
          data.scheduled = doc.data().meta.facebook.scheduled
      } else {
          console.log("No such document!");
      }
    }).catch((error) => {
        console.log("Error getting document:", error);
    });

    // Post on Facebook
    if(data.scheduled) {
      const message = data.message
      const access_token = data.accessToken
      axios.post('https://graph.facebook.com/1188810447962053/feed', {
        message,
        access_token
      })
      .then((response) => {
        res.send(200, 'Success - Posted on Facebook', response)
      })
      .catch((error) => {
        res.send(400, 'Error - Post on Facebook', error);
      });
    }
  })
});

回答1:


My Solution:

It turns out that the post request works just fine with the 'request-promise' npm package but it simply doesn't work with axios at all.

That's the respective code I'm using now:

const postToFacebook = {  
  method: 'POST',
  uri: `https://graph.facebook.com/${pageId}/feed`,
  qs: {
    access_token: access_token,
    message: postMessage
  }
};
request(postToFacebook)



回答2:


You can use axios within a firebase cloud function as follows:


exports.myFunction = functions.https.onRequest((req, res) => {
    return new Promise((resolve, reject) => {
        const payload = {
            "key": "value"
        };

        api.post("api.example.com", payload)
            .then(resolve)
            .catch(reject);
    });
});


来源:https://stackoverflow.com/questions/54786854/how-to-correctly-execute-a-axios-post-request-within-a-firebase-cloud-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!