NodeJs amazon-cognito-identity-js 注册成功而不返回结果



我已经从npm导入了node-fetch amazon-cognito-identitiy-js,并正在尝试部署自定义注册 lambda 函数。

global.fetch = require('node-fetch');
const AmazonCognitoIdentity = require('amazon-cognito-identity-js');
const poolData = {
  UserPoolId: "ap-southeast-1_******",
  ClientId: "***********"
}
module.exports.router = (event, context, callback) => {
  return createUser(event, context, callback);
};
function createUser(event, context, callback) {
  let postBody = JSON.parse(event.body);
  /*cognito test*/
  const userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);
  var attributeList = [];
  attributeList.push(new AmazonCognitoIdentity.CognitoUserAttribute({Name:"email",Value:postBody.email}));
  var cognitoResult = null;
  userPool.signUp(postBody.email, 'ke$2kelmDj123', attributeList, null, function(err, result){
      if (err) {
        cognitoResult = err;
      } else {
        cognitoResult = result;
      }
  });
  const response = {
    statusCode: 201,
    headers: {
      "Access-Control-Allow-Origin" : "*",
      "Access-Control-Allow-Credentials" : true
    },
    body: JSON.stringify({ message: "register account", special: postBody["name"], cognito: cognitoResult })
  };
  callback(null, response);
}

出于某种原因,cognitoResult只会返回 null,即使用户是在我在 AWS 的用户池中创建的。

那是因为这段代码

userPool.signUp(postBody.email, 'ke$2kelmDj123', attributeList, null, function(err, result){
      if (err) {
        cognitoResult = err;
      } else {
        cognitoResult = result;
      }
  });

是异步的,您不会等待结果。您只需在尚未解决此问题时返回响应。它最终会解析(您可以由正在创建的用户观察到(,但那时您已经从 Lambda 函数返回。

您可以通过在else块中嵌入响应来解决它。

userPool.signUp(postBody.email, 'ke$2kelmDj123', attributeList, null, function(err, result){
      if (err) {
        cognitoResult = err;
        // place error response here
      } else {
        cognitoResult = result;
        const response = {
          statusCode: 201,
          headers: {
            "Access-Control-Allow-Origin" : "*",
            "Access-Control-Allow-Credentials" : true
          },
          body: JSON.stringify({ message: "register account", special: postBody["name"], cognito: cognitoResult })
        };
        callback(null, response);
      }
  });

请注意,还应创建错误响应。

最新更新