使用 AWS Cognito 对用户进行身份验证时出现网络错误

KMC*_*KMC 5 reactjs amazon-cognito aws-sdk aws-cognito

我正在尝试将 Cognito 身份验证合并到我的基于 React 的项目中。我的代码基于 NPM 页面中给出的示例。这是它的样子:

var authenticationData = {
    Username : 'username',
    Password : 'password',
};

var authenticationDetails = new AmazonCognitoIdentity.AuthenticationDetails(authenticationData);

var poolData = {
    UserPoolId : '...', // Your user pool id here
    ClientId : '...' // Your client id here
};

var userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);

var userData = {
    Username : 'username',
    Pool : userPool
};

var cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData);
cognitoUser.authenticateUser(authenticationDetails, {
    onSuccess: function (result) {
               console.log('Successfully logged!');
            }
        });
    },

    onFailure: function(err) {
        console.log(JSON.stringify(err));
    },

});
Run Code Online (Sandbox Code Playgroud)

我创建了一个用户池并添加了一个应用程序客户端。我还为应用程序客户端启用了身份提供者。但是,我的代码无法通过错误{"code":"NetworkError","name":"Error","message":"Network error"}进行身份验证。由于我的项目仍然托管在本地主机上,我已经为 firefox 安装了 CORS 插件,但这并不能解决问题。我对这个错误消息没有多大意义。我已经仔细检查了 Cognito 区域、池 ID 和客户端 ID。它们都设置为正确的值。有没有人熟悉这个错误并且知道可能导致这个错误的原因?

小智 5

有点晚了,但我今天遇到了完全相同的错误,我花了一段时间才弄明白。当提交后发生自动刷新时会发生这种情况。这可以防止对 AWS Cognito 的 API 调用完成导致网络错误。

在启动认知功能之前,event.preventDefault();向您的代码添加一个。

例如,我在 addEventListener 中执行此操作:

document.querySelector("#authCognito").addEventListener("click", function(){
    var username = document.getElementById("userInput").value;
    var password = document.getElementById("passInput").value;
    var authenticationData = {
        Username: username,
        Password: password,
    };
    event.preventDefault();  
    cognitoAuthenticate(authenticationData);
});
Run Code Online (Sandbox Code Playgroud)