1

I have rerouted an external API call using Firebase Functions and everything seems to be working just fine (I have the paid plan) however, I am not sure how to pass parameters from the client side. The code on the server side looks like this:

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

exports.news = functions.https.onRequest((request, response) => {
  cors(request, response, () => {
    var config = {
      headers: {
        "X-Api-Key": functions.config().news.key,
      },
    };
    axios
      .get(
        "https://newsapi.org/v2/everything?q=usa&from=2021-08-27&to=2021-08-28&sortBy=popularity",
        config
      )
      .then((res) => {
        response.send(res.data);
      })
      .catch((error) => {
        response.sendStatus(error);
      });
  });
});

What I will be passing from the client side is the from and to dates which currently are hard coded in the url. Just to make sure, am I doing it right to make an API call from the client side using the generated link from the Firebase Functions: https://us-central1-<PROJECT-NAME>.cloudfunctions.net/news/?

Thanks in advance for all your replies.

2 Answers 2

1

You can pass those params as query parameters similar to the API call:

axios({
  method: 'get',
  url: 'the_cloud_function_url?from=the_date&to=another_date'
});

These query parameters can be access by request.query in the Cloud function.

Alternatively, you can make a POST request from Axios (client-side) and pass the data in body:

axios({
  method: 'post',
  url: 'the_cloud_function_url',
  data: {
    fromDate: '2021-08-27',
    toDate: '2021-08-29'
  }
});

This data can be read in cloud function using the request object:

exports.news = functions.https.onRequest((request, response) => {
  const {fromDate, toDate} = request.body

  console.log(fromDate, toDate)

  // continue
})
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, it's working, thanks! I used request.query :-)
0

Send data in body and handle the request.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.