首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >NodeJs amazon-cognito identity-js signUp成功但不返回结果

NodeJs amazon-cognito identity-js signUp成功但不返回结果
EN

Stack Overflow用户
提问于 2019-11-23 21:27:23
回答 1查看 813关注 0票数 0

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

代码语言:javascript
复制
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。

EN

回答 1

Stack Overflow用户

发布于 2019-11-24 00:20:27

这是因为这段代码

代码语言:javascript
复制
userPool.signUp(postBody.email, 'ke$2kelmDj123', attributeList, null, function(err, result){
      if (err) {
        cognitoResult = err;
      } else {
        cognitoResult = result;
      }
  });

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

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

代码语言:javascript
复制
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);
      }
  });

请注意,您还应该创建一个错误响应。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59008162

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档