【问题标题】:AWS Cognito returning undefined error async/awaitAWS Cognito 返回未定义错误 async/await
【发布时间】:2020-03-09 03:32:15
【问题描述】:

我的问题与this one 非常相似,因为我试图将authenticateUser SDK 方法包装在Promise 中并解决/拒绝它。

代码:

async function cognitoAuth(credentials, next, res) {
    const userData = {
        Username: credentials.email,
        Pool: userPool
    };
    const authenticationDetails = getAuthenticationDetails(credentials);

    let userCredentials;
    let authenticatedUserResponse;

    cognitoUser = new CognitoUser(userData);

    try {
        userCredentials = await checkIfAuthenticated(credentials.email);

        if (userCredentials.UserStatus === CognitoUserStatus.FORCE_CHANGE_PASSWORD) {
            res
                .status(203)
                .send(userCredentials);
        } else if (userCredentials.UserStatus === CognitoUserStatus.CONFIRMED) {
            authenticatedUserResponse = await authenticateUser(authenticationDetails);

            console.log(authenticatedUserResponse);
        }
    } catch(err) {
        if (err.message === CognitoErrorMessages.USER_NOT_EXIST) {
            next({
                name: err.message,
                status: 404
            });
        }
    }
}

如您所见,我有 2 个等待函数(checkIfAuthenticated 和 authenticateUser)。如果checkIfAuthenticated 抛出错误并拒绝承诺,那么catch 可以使用有效的err 对象。

但是,如果 authenticateUser 引发错误,则调用 catch 但未定义 err。

这是我的authenticateUser:

function authenticateUser(authenticationDetails) {
    return new Promise((resolve, reject) => {
        cognitoUser.authenticateUser(authenticationDetails, {
            onSuccess: (result) => {
                resolve(merge(err, {
                    res: "SUCCESS"
                }));
            },
            onFailure: (err) => {
                reject(merge(err, {
                    status: 401
                }));
            },
            newPasswordRequired: (userAttrs, requiredAttrs) => {
                resolve(merge(userAttrs, {
                    res: "NEW_PASS_REQ"
                }));
            }
        });
    });
}

使用断点,onFailure 被调用,它是正确的 err 对象,所以我不确定为什么它在 catch 中未定义

【问题讨论】:

    标签: javascript node.js aws-sdk


    【解决方案1】:

    想通了。我的一位同事指出,我通过在我的index.js (我的服务器入口点)中包含它来在我的服务器代码上运行 babel :

    require("@babel/polyfill");
    require("@babel/register");
    

    Node.js 中的转译问题。一旦我把它拿出来并切换到 ES5 导入/导出,它就可以正常工作了

    【讨论】:

      猜你喜欢
      • 2021-10-21
      • 1970-01-01
      • 2020-08-01
      • 2017-06-09
      • 2019-10-05
      • 2020-04-21
      • 1970-01-01
      • 1970-01-01
      • 2021-10-05
      相关资源
      最近更新 更多