2017-10-05 107 views
2

我試圖通過後端發送數據或獲取firebase雲端功能但無法使其工作。通過Ajax向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)); 
    })}); 
}); 

和IT控制檯日誌。

數據爲:未定義

體:{}

編輯:這裏是火力CONSOLE:

添加後:

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

enter image description here

+1

'方法:「GET」,'不是這應該是POST因爲你是在請求體 – Niladri

+2

使用數據傳遞'數據:{ mobileNo :「WzkyMzXXXXXXXXXXXc5ODBd」 }'而不是使用'body' – Niladri

+0

@Niladri,我已經嘗試了你的兩個建議。不工作:( –

回答

4

有幾個問題在你的代碼

  1. 變化的方法POST而不是GET在你的Ajax調用作爲要傳遞的數據請求主體

  2. 使用data屬性,而不是在ajax調用中調用body。它現在應該工作。該數據將在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); 
         } 
         }); 
    
+0

謝謝,工作: ) –

相關問題