节点函数不返回JSON对象

时间:2018-06-22 07:21:13

标签: json node.js express

这是我的库函数文件,名为verifyToken.js

require('dotenv').config();
const CognitoExpress = require("cognito-express");

//Initializing CognitoExpress constructor
const cognitoExpress = new CognitoExpress({
    cognitoUserPoolId: process.env.USER_POOL_ID, // User Pool id (created via Console->Cognito Manage User Pool)
    region: process.env.REGION, //User Pool Region
    tokenUse: "id", //Possible Values: access | id
    tokenExpiration: 3600000 //Up to default expiration of 1 hour (3600000 ms)
});

//Our middleware that authenticates all APIs under our 'authenticatedRoute' Router
module.exports = function(){
    this.verifyToken=(function(token, req, res) {

        //I'm passing in the id token in header under key Token
        let TokenFromClient = token;

        //Fail if token not present in header. 
        if (!TokenFromClient) return "Token missing from header";

        cognitoExpress.validate(TokenFromClient, function(err, response) {

            //If API is not authenticated, Return 401 with error message. 
            if (err) {
                return res.send({success:false, msg:"Token Authenication Error", Error:err});
            }

            //Else API has been authenticated. Proceed.
            return res.send({success:true, msg:"Token Authenication result", result: response});
        });
    });
}

我正在从控制器调用此功能

var verify_tokenController = {};

//Verify AWS token recieved through client header by calling verifyToken Library function
verify_tokenController.verify = function(req, res) {

    //Import verifyToken Library function
    require('../library/verifyToken')();

    var auth = verifyToken(req.header('Token'), req, res);
    console.log(auth);
};

module.exports = verify_tokenController;

但是我总是在控制台收到undefined。如何将err或响应返回给调用控制器。这两个返回变量都是JSON对象类型。

1 个答案:

答案 0 :(得分:0)

因为cognitoExpress.validateasync操作。它将运行,并且该函数的回调将运行。但是到那时,这一切都发生了。您的下一行

console.log(auth);已经命中,并且您看到未定义的原因,因为您当时实际上没有从verifyToken方法返回任何内容。

这是javascript和异步操作的工作方式。

您可以使用回调方法,但这不是我推荐的方法。因此,我正在用promises修改您的代码,看看它是否对您有用。

您的 verifyToken.js 应该如下所示:

require('dotenv').config();
const CognitoExpress = require("cognito-express");

//Initializing CognitoExpress constructor
const cognitoExpress = new CognitoExpress({
    cognitoUserPoolId: process.env.USER_POOL_ID, // User Pool id (created via Console->Cognito Manage User Pool)
    region: process.env.REGION, //User Pool Region
    tokenUse: "id", //Possible Values: access | id
    tokenExpiration: 3600000 //Up to default expiration of 1 hour (3600000 ms)
});

//Our middleware that authenticates all APIs under our 'authenticatedRoute' Router
module.exports = function(){
    this.verifyToken=(function(token, req, res) {
        return new Promise(function(resolve, reject) {
          //I'm passing in the id token in header under key Token
          let TokenFromClient = token;

          //Fail if token not present in header. 
          if (!TokenFromClient) return "Token missing from header";

          cognitoExpress.validate(TokenFromClient, function(err, response) {

              //If API is not authenticated, Return 401 with error message. 
              if (err)  {
                reject(err);
              } else {
                //Else API has been authenticated. Proceed.
                resolve(response);
              }                            

          });
        });            
    });
}

您的控制器应如下所示:

var verify_tokenController = {};

//Verify AWS token recieved through client header by calling verifyToken Library function
verify_tokenController.verify = function(req, res) {

    //Import verifyToken Library function
    require('../library/verifyToken')();

    verifyToken(req.header('Token'), req, res)
      .then(function(response){
        console.log(resposne, 'response')
        res.send({success:true, msg:"Token Authenication result", result: response});    
      })
      .catch(function(err) {
        res.send({success:false, msg:"Token Authenication Error", Error:err});
      });    
};

module.exports = verify_tokenController;

尝试上述解决方案。