使用 aws-cognito-identity-js 时获取类型错误
type error for fetch while using aws-cognito-identity-js
我正在使用 serverless framework
和 typescript
构建无服务器应用程序,并使用 aws cognito 进行用户身份验证。
当我在 local serverless environment
中使用应用程序时,一切正常。
我可以注册一个用户,也可以让用户登录以接收 jwt token
但是当我将代码部署到 aws 时,它给了我
"message": "fetch is not a function",
所以我经历了不同的 github 问题/堆栈溢出,看到每个人都通过添加 global.fetch 建议了类似的解决方案
post -> Nuxt application with amazon-cognito-identity-js package gives error fetch is not defined
中的类似解决方案
global.fetch = require('node-fetch')
const AmazonCognitoIdentity = require('amazon-cognito-identity-js');
所以我添加了上面的内容并安装了 node-fetch 并推送了代码
但问题是不同的,因为我使用的是打字稿,所以我不能使用 global.fetch
所以我找到了不同的方法来改变本地
Way 1
const globalAny:any = global;
globalAny.fetch = require('node-fetch');
Way 2
(global as any).fetch = require('node-fetch');
Way 3 -> Written at the end of this post.
当我在本地和 AWS LAMDA 中以两种方式 运行 时,它失败并出现相同的错误
TypeError: fetch is not a function
所以我别无选择,正在寻找是否有人可以帮助我。
较新版本的 node fetch 存在 webpack 问题,您可以在此线程中找到相关信息。 https://github.com/bitinn/node-fetch/issues/450
降级到 node-fetch@1.7.3
以使您的 Cognito 正常工作。
如果项目中使用了webpack,global.fetch就不行了。在应用程序根级别添加以下库。(推荐用于 serverless-webpack / lambda codestart 的任何其他网络包)
require('cross-fetch/polyfill');
我正在使用 serverless framework
和 typescript
构建无服务器应用程序,并使用 aws cognito 进行用户身份验证。
当我在 local serverless environment
中使用应用程序时,一切正常。
我可以注册一个用户,也可以让用户登录以接收 jwt token
但是当我将代码部署到 aws 时,它给了我
"message": "fetch is not a function",
所以我经历了不同的 github 问题/堆栈溢出,看到每个人都通过添加 global.fetch 建议了类似的解决方案 post -> Nuxt application with amazon-cognito-identity-js package gives error fetch is not defined
中的类似解决方案global.fetch = require('node-fetch')
const AmazonCognitoIdentity = require('amazon-cognito-identity-js');
所以我添加了上面的内容并安装了 node-fetch 并推送了代码
但问题是不同的,因为我使用的是打字稿,所以我不能使用 global.fetch
所以我找到了不同的方法来改变本地
Way 1
const globalAny:any = global;
globalAny.fetch = require('node-fetch');
Way 2
(global as any).fetch = require('node-fetch');
Way 3 -> Written at the end of this post.
当我在本地和 AWS LAMDA 中以两种方式 运行 时,它失败并出现相同的错误
TypeError: fetch is not a function
所以我别无选择,正在寻找是否有人可以帮助我。
较新版本的 node fetch 存在 webpack 问题,您可以在此线程中找到相关信息。 https://github.com/bitinn/node-fetch/issues/450
降级到 node-fetch@1.7.3
以使您的 Cognito 正常工作。
如果项目中使用了webpack,global.fetch就不行了。在应用程序根级别添加以下库。(推荐用于 serverless-webpack / lambda codestart 的任何其他网络包)
require('cross-fetch/polyfill');