首页 > 解决方案 > React Native 项目 - 无法通过自定义库使用 AwsAmplify 进行 API 调用

问题描述

我有一个名为 myapp 的 react-native 应用程序(没有 expo)。

我有一个名为 myapp-core 的私有自定义包,我在其中处理 AwsAmplify 服务(Auth、Storage)——用于登录/signOut/等。

我想在 myapp 项目中使用 myapp-core,所以我将它添加为package.json( "myapp-core": "file:../myapp-core",) 中的依赖项,然后yarn install.

我面临的问题是,当我myapp-core.authService.login(username, password)从移动项目调用时,我发现了错误:

“ { “line”:177826, “column”: 17, “sourceURL”: “<a href="http://10.0.2.2:8081/index.delta?platform=android&dev=true&minify=false" rel="nofollow noreferrer">http://10.0.2.2:8081/index.delta?platform=android&dev=true&minify=false” } ”</p>

根据我的研究,这意味着我的自定义库无法进行 api 调用——但我并不确切知道。

当我直接在我的移动项目中使用 aws-amplify 的 Auth 对象时,它可以工作。

希望相关代码:

/**=============================**/
/** myapp/CoreServices.js **/

import { AmplifyService } from “myapp-core";

export default class CoreServices {

 constructor() {

    AmplifyService.configure();
    const auth = AmplifyService.authService();

    auth
      .login(“myusername”, “mypassword”)
      .then(user => console.warn("success", user))
      .catch(error => console.warn("error", error));
  }
}


/**=============================**/
/** myapp-core/AmplifySevice.js **/

import Amplify from 'aws-amplify';
import AuthService from '../AuthService/AuthService';
import awsConfigs from '../aws-exports';

class AmplifyService {

  static authServiceInstance = null;
  static storageServiceInstance = null;

  static configure(config = awsConfigs) {
    if (config === null || config === undefined) {
      throw new Error('AmplifyService must be initialized with Auth and Storage configurations.');
    }
    Amplify.configure({
      Auth: { /*...*/ },
      Storage: { /*...*/ }
    });
  }

  static authService() {
    if (!this.authServiceInstance) {
      this.authServiceInstance = new AuthService();
    }
    return this.authServiceInstance;
  }

  static storageService() {
    console.warn('storage service');
    //  initialize storage service
    //  return storage service
  }
}

标签: react-nativeauthenticationpackageaws-amplify

解决方案


我设法解决了我的项目问题。也许有人会从我的解决方案中受益。

问题与 AwsAmplify 没有任何关系,而是与我链接项目的方式有关:myapp-coremyapp.

问题是,在myapp-core我使用的aws-amplify包中,我通常会链接到移动项目(react-native link),但在我的情况下,我(错误地)认为情况并非如此。

解决方案是链接 iOS/Android 项目中需要的任何包以安装正确的 pods/gradle 库,例如react-native link amazon-cognito-identity-js用于身份验证。

...现在我终于高兴了:))

提供一些启示的链接:

如果有人认为这不是解决方案,而我很幸运,请发表评论或发表其他回复。


推荐阅读