通过Ajax将数据发送到Firebase云功能

时间:2017-10-05 11:27:46

标签: javascript jquery ajax google-cloud-functions

我正在尝试通过帖子发送数据或获取 firebase云功能,但无法使其正常工作。

这是我的 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);
            }
          });

这是云功能:

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));
    })});
});

它控制台日志。

  

DATA IS:undefined

     

BODY IS:{}

编辑:这里是火灾控制台:

添加后:

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

enter image description here

1 个答案:

答案 0 :(得分:5)

您的代码中存在一些问题

  1. 在您的ajax调用中将方法更改为POST而不是GET,因为您在请求正文中传递数据

  2. 在ajax调用中使用data属性而不是body。它现在应该工作。数据将在firebase函数

    中的request.body中提供
    $.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);
            }
          });