Noman Ali
Noman Ali

Reputation: 3340

Sending data to Firebase Cloud Function via Ajax

I am trying to send data through post OR get to firebase cloud function but couldn't get it work.

Here is my ajax:

       $.ajax({
            url: 'https://us-ceXXX1-reXXXts-fXXa-pr.cloudfunctions.net/helloWorld',
            dataType: "json",
            method: 'GET',
            crossDomain: true,
            body: {
                mobileNo: "WzkyMzXXXXXXXXXXXc5ODBd"
            },
            success: function(data){
              console.log('succes: '+data);
            }
          });

And Here Is Cloud Function:

exports.helloWorld = functions.https.onRequest((request, response) => {
    var responsez = response;

    console.log("DATA IS:"+request.data);    //prints undefined
    console.log("BODY IS:"+JSON.stringify(request.body));  //prints BODY ID: {}
    var mobNo = request.body.mobileNo;
    var options = {
      body: {mobileNo: mobNo, applicationVersion: "1.0"},
      url: 'http://nxxxpi.fixxxa.wxb.pk/GetxxxxxxoUxr',
      headers: {
            'appKey':'jDxxxxxxxOr',
            'appId':'2xxxxx9'
      },
      json: true
    }
    cors(request, response, () => {requestz.post(options, function (error, response, body) {
      console.log('error:', error); // Print the error if one occurred
      console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
      console.log('body:', body); // Print the HTML for the Google homepage.
      responsez.send(JSON.stringify(body));
    })});
});

And It console logs.

DATA IS: undefined

BODY IS: {}

EDIT: HERE IS THE FIREBASE CONSOLE:

After adding:

console.log("BODY MOBILE:"+JSON.stringify(request.body.mobileNo));
console.log("ONLY MOBILE:"+JSON.stringify(request.mobileNo));

enter image description here

Upvotes: 2

Views: 3483

Answers (1)

Niladri
Niladri

Reputation: 5962

There are few issues in your code

  1. change the method to POST instead of GET in your ajax call as you are passing the data in request body

  2. use the data property instead of body in the ajax call . it should work now. The data will be available in request.body inside the firebase function

    $.ajax({
            url: 'https://us-ceXXX1-reXXXts-fXXa-pr.cloudfunctions.net/helloWorld',
            dataType: "json",
            method: 'POST',
            crossDomain: true,
            data: {
                mobileNo: "WzkyMzXXXXXXXXXXXc5ODBd"
            },
            success: function(data){
              console.log('succes: '+data);
            }
          });
    

Upvotes: 5

Related Questions