全局变量scope返回[Object object]而不是node.js中的字符串

时间:2018-05-30 07:29:43

标签: android node.js

我正在尝试访问请求函数中的tokenName,我能够成功响应。但我想全局访问它,所以我可以将它保存在数据库中。

   request(options,function (error, response, body) {
    tokenName = body.notification_key; 
    console.log('tokenName: ' + tokenName); //I get the token name successfully
    return tokenName;
    });




        var data = {

                image: image,
                email: token_email,
                name: name1,
                notification_key: tokenName,   //now, here it returns [Object object],dont know why
                token_id: token_id1,
                extra: 'created'
                };
             console.log('image : ' + image);
             console.log('email : ' + token_email);
             console.log('name : ' + name1);
             console.log('tokenName : ' + tokenName);      //gives[Object object]
             console.log('token_id : ' + token_id1);

             return db.collection('Users').doc(user_id).set(data); //could not save because of this

JSON的主体就像

{ notification_key: ‘WPX91bFxpiCMFe5p6JjypsOSgXn2lCVHMrX5Q1d-fjYqFoHMMc-
DjE8S97GJiCs0lw0DPGnckSGe_AQhhOViV5MF67Rodb9bNlCPmYt2UUi2-
vPmrwncYJs7NqdZE7DyuO3sZ0e_b98c’ }

enter image description here

我在node.js中表现不佳。

1 个答案:

答案 0 :(得分:0)

你应该全局定义'tokenName'以在函数外部使用它,你应该将tokenName转换为字符串以将其保存在数据库中,如下所示: -

let tokenName; // i set this variable at global level


request(options,function (error, response, body) {

tokenName = body.notification_key; // asing the valeu to the global variable

console.log('tokenName: ' + tokenName); 

});




    var data = {

            image: image,
            email: token_email,
            name: name1,
            notification_key: tokenName,   //now it return token (string)
            token_id: token_id1,
            extra: 'created'
            };
         console.log('image : ' + image);
         console.log('email : ' + token_email);
         console.log('name : ' + name1);
         console.log('tokenName : ' + tokenName);      
         console.log('token_id : ' + token_id1);

         return db.collection('Users').doc(user_id).set(data);