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