【问题标题】:Fetch API not working with Proguard获取 API 不与 Proguard 一起使用
【发布时间】:2021-04-09 13:40:38
【问题描述】:

打开 proguard 后,fetch API 不起作用。下面是代码sn -p

try {
const response = await fetch(url, {
      method: 'GET',
      headers: {
        'Content-Type': "application/json",
        'Accept': 'application/json'
      }
    });    
} catch (err) {
  console.log(err)
}

我能够跟踪调试器直到 fetch 调用。但在那之后既没有错误也没有响应。控制台中也没有错误/警告。非常感谢有关如何调试/解决此问题的任何帮助。

我正在使用 RN v0.55.4(最新)

【问题讨论】:

    标签: react-native proguard react-native-android android-proguard fetch-api


    【解决方案1】:

    添加了下面的 proguard 规则来解决这个问题

    -optimizations !method/*/*,!code/*/*

    【讨论】:

      【解决方案2】:

      fetch() 方法接受一个强制参数,即您要获取的资源的路径。它返回一个 Promise,该 Promise 解析为对该请求的响应,无论它是否成功。

      you need to modify like below
      
      fetch(url)
        .then((resp) => resp.json()) // Transform the data into json
        .then(function(data) {
          // your code logic with the response
          })
        })
      

      【讨论】:

      • 我知道这一点。如果您看到,在 fetch 调用之前有一个 await 。它永远不会回来。即承诺永远不会被解决/拒绝
      • 它是否抛出任何错误,例如 undefined 或其他任何错误
      • 使用您尝试访问的 URL 更新您的问题
      【解决方案3】:

      启用 Proguard 后(Android 发布版本默认启用),它可以在缩小过程中重命名 BuildConfig Java 类并阻止 Fetch 引用它。

      为避免这种情况,请在 android/app/proguard-rules.pro 中添加一个例外:

       -keep class com.mypackage.BuildConfig { *; }
      

      此包名应与您应用的包名相同。

      还要添加 Okhttp3 和 Okio 的 Progurad 规则。

      对于 React Native 项目,最终的 proguard 可能看起来像这样

      -keep public class com.horcrux.svg.** {*;}
      -keep class com.facebook.react.turbomodule.** { *; }
      
      -dontwarn okio.**
      -keep class com.swiggyvendorapp.BuildConfig { *; }
      -dontwarn com.squareup.okhttp.**
      -keep class com.squareup.okhttp.** { *; }
      -keep interface com.squareup.okhttp.** { *; }
      -dontwarn retrofit.**
      -dontwarn retrofit.appengine.UrlFetchClient
      -keep class retrofit.** { *; }
      -keepclasseswithmembers class * {
          @retrofit.http.* <methods>;
      }
      -keepattributes Signature
      -keepattributes *Annotation*
      

      【讨论】:

        猜你喜欢
        • 2015-02-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多