处理Amazon Cognito登录认证出现的错误

总结

假设您使用Cognito进行应用程序的登录验证。

在进行其实现时,我使用 npm install 安装了 Cognito 的 Javascript SDK,即 amazon-cognito-identity-js,然后我在应用中加载了这个库。但是,当我启动应用时,出现了错误。

我想要写下那时的应对方法。

在这里,对登录处理的实现部分进行省略。

假设

应用程序:Angular、Typescript
需要使用npm install安装的库:aws-sdk、amazon-cognito-identity-js

・确保使用Angular CLI的ng generate生成的Angular应用程序。
・确保已经在Cognito中创建了用户池和用户,并且已处于可以登录的状态。

步驟.

在应用程序中通过npm install命令安装aws-sdk和amazon-cognito-identity-js库,然后在任意文件中导入这两个库。
*这里省略了登录功能的实现部分。
如果在Cognito登录实现等方面进行搜索,在Qiita或其他网站上都可以找到各种实现方法,请参考它们。

以下是两个库的部分导入代码:

以下是从两个库中抽取的部分导入代码。

import { CognitoUserPool, CognitoUserAttribute, CognitoUser, AuthenticationDetails }  from "amazon-cognito-identity-js";
import * as AWS from 'aws-sdk';

之后我试图用ng serve启动应用程序,但是出现了错误。

错误1:出现与流、缓冲区相关的错误,导致在终端输出并编译出错。

以下的错误连续地输出到终端,导致无法编译。

Error: node_modules/aws-sdk/lib/http_response.d.ts:1:25 - error TS2307: Cannot find module 'stream' or its corresponding type declarations.
1 import * as stream from 'stream';
                          ~~~~~~~~

Error: node_modules/aws-sdk/lib/http_response.d.ts:14:18 - error TS2591: Cannot find name 'Buffer'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node` and then add 'node' to the types field in your tsconfig.
14     body: string|Buffer|Uint8Array;
                    ~~~~~~

Error: node_modules/aws-sdk/lib/request.d.ts:1:25 - error TS2307: Cannot find module 'stream' or its corresponding type declarations.
1 import * as stream from 'stream';
                          ~~~~~~~~

Error: node_modules/aws-sdk/lib/request.d.ts:145:45 - error TS2591: Cannot find name 'Buffer'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node` and then add 'node' to the types field in your tsconfig.

....

** Angular Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200/ **

✖ Failed to compile.

解决方法

Error: node_modules/aws-sdk/lib/request.d.ts:145:45 
error TS2591: Cannot find name 'Buffer'. Do you need to install
type definitions for node? Try `npm i --save-dev @types/node` and
then add 'node' to the types field in your tsconfig.

根据上述错误的输出信息,执行@types/node的安装步骤。

npm i --save-dev @types/node

将”node”添加到tsconfig.json的compilerOptions.types部分。
*由于其他值根据环境而异,因此省略了。

 {
   	"compilerOptions ": {
   		"types": [
   			"node"
   		]
 },
   	"angularCompilerOptions": {}
 }

如果你再次使用`ng serve`命令启动应用,应该就能消除错误了。

错误2:浏览器控制台显示global未定义的错误,导致页面无法显示。

我根据这个网站提供的参考编写了使用Cognito进行登录的代码。

image.png

解决方案

请在index.html文件中添加以下代码。

<script>
  if (global === undefined) {
    var global = window;
  }
</script>

<!-- ここから下はデフォルトのままdoctype html を宣言してhtmlを記載しました -->
<!doctype html>
<html lang="en">
    ...省略...
</html>

经过调查发现,
这个问题也在git的issue上遇到了。
最新的Angular 6 RC #678中发生了Uncaught ReferenceError: global未定义的错误。

Angular的GitHub上还有关于全局错误的信息。

在使用外部库时,似乎无法找到全局对象并导致出错。

广告
将在 10 秒后关闭
bannerAds