1

我在客戶端運行以下代碼以訪問數據庫內用戶的屬性。AJAX獲取請求無法識別提交的數據?

firebaseAUTH.signInWithEmailAndPassword(email, password).then(function (user) { 
console.log('user has signed in with e-mail address: '+user.email+' and user ID: '+user.uid) 
firebaseAUTH.currentUser.getToken(true).then(function(idToken) { 
$.ajax(
    { 
// Send token to your backend via HTTPS (JWT) 
     url: '/auth', 
     type: 'POST', 
     data: {token: idToken}, 
     success: function (response){ 
     var userID = response.userID 
    firebase.database().ref('/users/' + userID).once('value').then(function(snapshot) { 
    var industry = snapshot.val().industry 
    var company = snapshot.val().company 
    var firstname = snapshot.val().firstname 
    var email = snapshot.val().email 
    var source = snapshot.val().source 
    var phone = snapshot.val().phone 
    var password = snapshot.val().password 
    var lastname = snapshot.val().lastname 
     $.get(
     { 
      url: '/members-area/'+userID, 
      data: {userID: userID, 
       industry: industry, 
       email: email}, 
      success: function(response){ 
      window.location = '/members-area/'+userID 
      } 
     }) 

我的服務器端代碼:

app.get('/members-area/:userID', function(req,res,next) { 
    res.render('members-area', { userID: req.params.userID, industry: req.params.industry, email: req.params.email})                 
}) 

然而,當我嘗試訪問哈巴狗的「產業」變量,它顯示了不確定的。正如你所看到的,我在GET ajax調用中發送它,那麼問題是什麼?這也很奇怪,因爲我在函數快照之後將控制檯的變量名稱'登錄到控制檯,並且他們在那裏。另外,神祕的'userID'顯示爲內容變量,但'行業'和'電子郵件'根本沒有。

回答

2

我不太清楚你想做什麼,但希望我可以幫助一些。

首先你不需要第二次電話來獲取令牌。當您調用signInWithEmailAndPassword時,Firebase會返回用戶。所以,你可以調用爲gettoken馬上

firebaseAUTH.signInWithEmailAndPassword(email, password).then(function (user) { 
console.log('user has signed in with e-mail address: '+user.email+' and user ID: '+user.uid) 
console.log('we also got the token: ' + user.getToken()); 
... 

你似乎也張貼到一個沒有被定義的路由,然後你用查詢得到一個不同的路線。

此外,神祕'userID'顯示爲帶有內容的var,但 '行業'和'電子郵件'完全沒有。

在您的服務器端代碼中,您的路由僅使用一個參數定義:userID。該行

app.get('/members-area/:userID', function(req,res,next) 

將userID定義爲參數,而不是其他2個變量。所以它是有道理的,他們是未定義的。

我認爲你要做的是:

firebaseAUTH.signInWithEmailAndPassword(email, password).then(function (user) { 
    const userId = user.getToken(); 
    firebase.database().ref('/users/' + userID).once('value').then(function(snapshot) { 
     $.post('/members-area/' + userId, snapshot.val(), function(data, status) { 
      console.log(data); 
      console.log(status); 
    }); 
}); 

然後在你的服務器代碼:

app.post('/members-area/:userID', function(req,res,next) { 
    const theSnapshot = req.body; 
    res.send(theSnapshot) 
}); 

我還是不明白,你爲什麼會想使用以檢索信息來自數據庫的客戶端代碼,然後僅將其發佈到服務器以再次獲取它。但也許我誤解了一些東西:)

它也很奇怪看到發送數據的請求,我敢肯定它的規格。你通常想用post發送數據然後用get來獲取數據:)

+0

非常感謝!這正是我需要的。 – huzal12

+0

很高興幫助。如果您對此感到滿意,請將其標記爲已接受的答案? – Bergur

+0

我應該使用發佈還是獲得私人/受保護的頁面,即是否有任何約定?我認爲這將是GET,因爲這是有道理的:加載一個新的頁面(從系統中檢索信息)。 – huzal12