我已经从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。
发布于 2019-11-24 00:20:27
这是因为这段代码
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);
}
});请注意,您还应该创建一个错误响应。
https://stackoverflow.com/questions/59008162
复制相似问题