1

I am setting up Firebase cloud functions to make API calls to a non-google service. For testing I am using jsonplaceholder as the API. the response I am receiving is a 403 error.

I have looked at other problems similar to this but the answer stated upgrading to a paid firebase account would fix the problem. Upon upgrading to the blaze plan I fixed the Firebase blocking outgoing http calls but I now am stuck at the 403 error being returned by any API I have tried making requests from.


import * as functions from 'firebase-functions';
const cors = require('cors')({origin: true});

export const getJson = functions.https.onRequest(async (req, res) => {
    cors( req, res, async ()=> {
        try {
            let info = await req.get('https://jsonplaceholder.typicode.com/todos/1');
            res.send(info);
        } catch (error) {
            res.status(500).send(`catch block hit: ${error}`);
        }
    })
})

I expected the API call to return a json object:

{
  "userId": 1,
  "id": 1,
  "title": "delectus aut autem",
  "completed": false
}

what I am receiving back is:

 "Failed to load resource: the server responded with a status of 403 ()"

NOTE: I can receive the expected result if I make the get request from postman

Your help is appreciated, thanks.

  • Possible duplicate of [How to fetch a URL with Google Cloud functions? request?](https://stackoverflow.com/questions/54275148/how-to-fetch-a-url-with-google-cloud-functions-request) – Renaud Tarnec Aug 20 '19 at 09:09
  • See also some similar answers here https://stackoverflow.com/questions/56410014/how-to-make-get-request-firebase-cloud-functions/56414318#56414318 and here https://stackoverflow.com/questions/56867732/how-to-grab-json-file-from-external-urlplaces-api-using-firebase-functions/56872063#56872063 – Renaud Tarnec Aug 20 '19 at 09:12

1 Answers1

0

req is the request sent to the server, and req.get() is used to get the headers of that request. If you want to make a request, you need to fire off your own. You can do that with raw node (eg, https package) or bring in a package like axios or isomorphic-fetch. Something like this:

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

export const getJson = functions.https.onRequest(async (req, res) => {
  cors( req, res, async ()=> {
    try {
      let info = await axios.get('https://jsonplaceholder.typicode.com/todos/1');
      res.send(info.data);
    } catch (error) {
      res.status(500).send(`catch block hit: ${error}`);
    }
  })
})
I'm Joe Too
  • 5,468
  • 1
  • 17
  • 29