Noman Ali
Noman Ali

Reputation: 3340

Pass data to nodejs server from javascript file - Nodejs

I have been fighting with an (firebase & nodejs) issue and it's 4th part of that problem, How can i pass data after login to server.js

I have tried this But failed to get it working.

Basically i am trying to send user idToken to server to get it verified.

This what i have tried:

const promise = auth.signInWithEmailAndPassword(email, pass).then(function(){
    $('.load-bar').hide();
    firebase.auth().currentUser.getIdToken(/* forceRefresh */ true).then(function(idToken) {
        // Send token to your backend via HTTPS
        console.log(data);
        $http.get('server', {params: {idToken: idToken}})
            .success(
                function(success){
                    console.log('success');
                })
            .error(
                function(error){
                    console.log(error)
                });
    }).catch(function(error) {
      // Handle error
    });
});

But it's doing nothing no error not success and on server.js

app.get('/server', function(req,res, next){
   console.log(req.query.idToken);
});

But still nothing. What am i doing wrong?

Upvotes: 0

Views: 269

Answers (3)

user6259970
user6259970

Reputation:

The issue is you are not sending your response back to the api call origin. That is why you are not getting success or error results.

Change the code in server as:

app.get('/server', function(req, res, next){
   console.log(req.query.idToken);
   res.send(200);/*Just sends success code*/
   //res.send("Token rcvd");/*Or send some custom message back to call origin*/
});

Upvotes: 0

shawon191
shawon191

Reputation: 1955

If you don't return Promise from then, the Promise will return undefined. And to resolve a promise with success you need to return Promise.resolve and to terminate with error you need to return Promise.reject. Try this -

const promise = auth.signInWithEmailAndPassword(email, pass).then(function(){
    $('.load-bar').hide();
    return firebase.auth().currentUser.getIdToken(/* forceRefresh */ true).then(function(idToken) {
        // Send token to your backend via HTTPS
        console.log(data);
        $http.get('server', {params: {idToken: idToken}})
            .success(
                function(success){
                    return Promise.resolve(success);
                })
            .error(
                function(error){
                    return Promise.reject(error);
                });
    }).catch(function(error) {
      return Promise.reject(error);
    });
});

Upvotes: 1

Ezra Chu
Ezra Chu

Reputation: 822

Your route needs to respond:

app.get('/server', function(req,res, next){
  console.log(req.query.idToken);
  return res.send('success!');
});

Upvotes: 0

Related Questions