Ad

Firebase Cloud Functions: Cannot Use JSON Output Of Http.get Request Via Axios

I am unable to use the JSON output of an external Axios.get request in Firebase Cloud Function.

The function below gives the desired output when run locally (when the part creating a document in Cloud Firestore is removed) but results in an error when deployed.

TypeError: Cannot read property 'user' of undefined at axios.get.then.resultData (/srv/index.js:13:52)

This means that the ".then" executes before the JSON is retrieved from ".get".

I do not understand why the function gives the desired output (First Image URL) when run locally or in emulator but not in live deployment.

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const axios = require('axios').default;

exports.createEvent = functions.https.onRequest(async (req, res) => {
     axios
        .get("https://www.instagram.com/cristiano/?__a=1")
        .then(resultData => {
                let post = resultData.data.graphql.user.edge_owner_to_timeline_media.edges;
                img_url = post[0].node.display_url;
                if (post[0].node.edge_media_to_caption.edges[0]) {
                    caption = post[0].node.edge_media_to_caption.edges[0].node.text;
                }
                let newDoc = {
                    post_number: parseInt(0),
                    url: img_url,
                    caption: caption
                }
                return admin.firestore().collection('events').doc().create(newDoc) })
         .then(res.json({result: `Success`}))
        .catch(err => {
            console.log(err);
            res.status(500).send(err)
        });
    })

I am on the paid Blaze plan and I have installed Axios using npm.

I have tried many ways including using promises and rewriting my code, but I have yet to find a way to get my desired output written to Cloud Firestore. Can anyone suggest a way that works?

EDIT After reply from @Quentin, I logged resultData.data and got this:

<!DOCTYPE html>
<html lang="en" class="no-js not-logged-in client-root">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">

        <title>
Login • Instagram
</title>

        
        <meta name="robots" content="noimageindex, noarchive">
        <meta name="apple-mobile-web-app-status-bar-style" content="default">
        <meta name="mobile-web-app-capable" content="yes">
        <meta name="theme-color" content="#ffffff">
        <meta id="viewport" name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1, viewport-fit=cover">
        <link rel="manifest" target="_blank" rel="nofollow noreferrer" href="/data/manifest.json">

        <link rel="preload" target="_blank" rel="nofollow noreferrer" href="/static/bundles/metro/ConsumerUICommons.css/bd4841937f28.css" as="style" type="text/css" crossorigin="anonymous" />
<link rel="preload" target="_blank" rel="nofollow noreferrer" href="/static/bundles/metro/ConsumerAsyncCommons.css/638f1bd337c8.css" as="style" type="text/css" crossorigin="anonymous" />
<link rel="preload" target="_blank" rel="nofollow noreferrer" href="/static/bundles/metro/Consumer.css/39b2171a177c.css" as="style" type="text/css" crossorigin="anonymous" />
<link rel="preload" target="_blank" rel="nofollow noreferrer" href="/static/bundles/metro/FBSignupPage.css/5e365c4760d1.css" as="style" type="text/css" crossorigin="anonymous" />
<link rel="preload" target="_blank" rel="nofollow noreferrer" href="/static/bundles/metro/LoginAndSignupPage.css/6a800c588f0a.css" as="style" type="text/css" crossorigin="anonymous" />
<link rel="preload" target="_blank" rel="nofollow noreferrer" href="/static/bundles/metro/Vendor.js/5a56d51ae30f.js" as="script" type="text/javascript" crossorigin="anonymous" />
<link rel="preload" target="_blank" rel="nofollow noreferrer" href="/static/bundles/metro/en_US.js/944962edb876.js" as="script" type="text/javascript" crossorigin="anonymous" />
<link rel="preload" target="_blank" rel="nofollow noreferrer" href="/static/bundles/metro/ConsumerLibCommons.js/35c20f5c7f34.js" as="script" type="text/javascript" crossorigin="anonymous" />
<link rel="preload" target="_blank" rel="nofollow noreferrer" href="/static/bundles/metro/ConsumerUICommons.js/b823fe79c3d7.js" as="script" type="text/javascript" crossorigin="anonymous" />
<link rel="preload" target="_blank" rel="nofollow noreferrer" href="/static/bundles/metro/ConsumerAsyncCommons.js/29f22e89b63f.js" as="script" type="text/javascript" crossorigin="anonymous" />
<link rel="preload" target="_blank" rel="nofollow noreferrer" href="/static/bundles/metro/Consumer.js/1a38f40c2194.js" as="script" type="text/javascript" crossorigin="anonymous" />
<link rel="preload" target="_blank" rel="nofollow noreferrer" href="/static/bundles/metro/FBSignupPage.js/1b9285c96c9c.js" as="script" type="text/javascript" crossorigin="anonymous" />
<link rel="preload" target="_blank" rel="nofollow noreferrer" href="/static/bundles/metro/LoginAndSignupPage.js/311eeb6a3843.js" as="script" type="text/javascript" crossorigin="anonymous" />
        <link rel="prefetch" as="script" target="_blank" rel="nofollow noreferrer" href="/static/bundles/metro/FeedPageContainer.js/f27b7d9347b6.js" type="text/javascript" crossorigin="anonymous" />
<link rel="prefetch" as="stylesheet" target="_blank" rel="nofollow noreferrer" href="/static/bundles/metro/FeedPageContainer.css/b9260d9c2d3e.css" type="text/css" crossorigin="anonymous" />
        

        <script type="text/javascript">
        (function() {
  var docElement = document.documentElement;
  var classRE = new RegExp('(^|\\s)no-js(\\s|$)');
  var className = docElement.className;
  docElement.className = className.replace(classRE, '$1js$2');
})();
</script>
        <script type="text/javascript">
(function() {
  if ('PerformanceObserver' in window && 'PerformancePaintTiming' in window) {
    window.__bufferedPerformance = [];
    var ob = new PerformanceObserver(function(e) {
      window.__bufferedPerformance.push.apply(window.__bufferedPerformance,e.getEntries());
    });
    ob.observe({entryTypes:['paint']});
  }

  window.__bufferedErrors = [];
  window.onerror = function(message, url, line, column, error) {
    window.__bufferedErrors.push({
      message: message,
      url: url,
      line: line,
      column: column,
      error: error
    });
    return false;
  };
  window.__initialData = {
    pending: true,
    waiting: []
  };
  function asyncFetchSharedData(extra) {
    var sharedDataReq = new XMLHttpRequest();
    sharedDataReq.onreadystatechange = function() {
          if (sharedDataReq.readyState === 4) {
            if(sharedDataReq.status === 200){
              var sharedData = JSON.parse(sharedDataReq.responseText);
              window.__initialDataLoaded(sharedData, extra);
            }
          }
        }
    sharedDataReq.open('GET', '/data/shared_data/', true);
    sharedDataReq.send(null);
  }
  function notifyLoaded(item, data) {
    item.pending = false;
    item.data = data;
    for (var i = 0;i < item.waiting.length; ++i) {
      item.waiting[i].resolve(item.data);
    }
    item.waiting = [];
  }
  function notifyError(item, msg) {
    item.pending = false;
    item.error = new Error(msg);
    for (var i = 0;i < item.waiting.length; ++i) {
      item.waiting[i].reject(item.error);
    }
    item.waiting = [];
  }
  window.__initialDataLoaded = function(initialData, extraData) {
    if (extraData) {
      for (var key in extraData) {
        initialData[key] = extraData[key];
      }
    }
    notifyLoaded(window.__initialData, initialData);
  };

Why does Instagram block request from Firebase even when it runs only once?

Ad

Answer

Ok, I have logged (resultData.data) and I got <!DOCTYPE html> <html lang="en" class="no-js not-logged-in client-root">

I guess this mean that Instagram does not allow requests from Firebase server but allows request from my local computer?

No. It means it doesn't allow requests when you are not logged in.

The browser is logged in so requests coming from there get the JSON you expect.

The Firebase server isn't logged in, so requests coming from there get an error message.

You need to login to get the data. The getting started guide covers how to do that.

Ad
source: stackoverflow.com
Ad