当我使用react-native init (RN版本0.29.1)创建一个全新的项目,并在渲染方法中获取公共facebook演示电影API时,它抛出了一个网络请求失败。有一个非常无用的堆栈跟踪,我不能调试网络请求在chrome控制台。这是我发送的fetch:

fetch('http://facebook.github.io/react-native/movies.json')
      .then((response) => response.json())
      .then((responseJson) => {
        return responseJson.movies;
      })
      .catch((error) => {
        console.error(error);
      });

当前回答

对于Android设备,进入您的项目根文件夹并运行命令:

adb reverse tcp:[your_own_server_port] tcp:[your_own_server_port]

例如:adb reverse tcp:8088 tcp:8088

这将使您的物理设备(即。Android手机)监听本地主机服务器运行在您的开发机器(即您的计算机)地址http://localhost:[your_own_server_port]。

之后,你可以直接在react-native fetch()调用中使用http:localhost:[your_port] /your_api。

其他回答

不建议允许http的所有域。 只对必要的域进行例外处理。

来源:在iOS 9和OSX 10.11中配置应用程序传输安全例外

将以下内容添加到信息中。你的应用的Plist文件:

<key>NSAppTransportSecurity</key>
<dict>
  <key>NSExceptionDomains</key>
  <dict>
    <key>yourserver.com</key>
    <dict>
      <!--Include to allow subdomains-->
      <key>NSIncludesSubdomains</key>
      <true/>
      <!--Include to allow HTTP requests-->
      <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
      <true/>
      <!--Include to specify minimum TLS version-->
      <key>NSTemporaryExceptionMinimumTLSVersion</key>
      <string>TLSv1.1</string>
    </dict>
  </dict>
</dict>

对于Android设备,进入您的项目根文件夹并运行命令:

adb reverse tcp:[your_own_server_port] tcp:[your_own_server_port]

例如:adb reverse tcp:8088 tcp:8088

这将使您的物理设备(即。Android手机)监听本地主机服务器运行在您的开发机器(即您的计算机)地址http://localhost:[your_own_server_port]。

之后,你可以直接在react-native fetch()调用中使用http:localhost:[your_port] /your_api。

通过在0.0.0.0上运行模拟服务器 注意:当你使用json-server运行另一个服务器时,这在Expo上有效。

另一种方法是在0.0.0.0而不是localhost或127.0.0.1上运行模拟服务器。

这使得模拟服务器可以在LAN上访问,因为Expo要求开发机器和运行Expo应用程序的移动设备在同一个网络上,所以模拟服务器也可以访问。

在使用json-server时,可以使用以下命令实现这一点

Json-server——host 0.0.0.0——port 8000 ./db。json,看

请访问此链接了解更多信息。

修复TypeError:在Android调试版本中将文件上传到http而不是https时网络请求失败

在react-native 0.63.2(我正在测试)或更高版本中,如果只是使用fetch将文件上传到http(而不是https)服务器,将会遇到TypeError:网络请求失败。

在这里,我使用axios@0.27.2作为运行在Android手机上的客户端,成功地将文件上传到react-native-file-server作为运行在另一台Android手机上的服务器。

客户端需要编辑JAVA和JS代码,服务器不需要编辑JAVA代码。

在调试构建中,必须注释掉这个文件android/app/src/debug/java/com/YOUR_PACKAGE_NAME/ReactNativeFlipper.java中的43行

38      NetworkFlipperPlugin networkFlipperPlugin = new NetworkFlipperPlugin();
39      NetworkingModule.setCustomClientBuilder(
40          new NetworkingModule.CustomClientBuilder() {
41            @Override
42            public void apply(OkHttpClient.Builder builder) {
43      //        builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin));
44            }
45          });
46      client.addPlugin(networkFlipperPlugin);

也许还需要添加android:usesCleartextTraffic="true"下的<应用程序的android/app/src/main/AndroidManifest.xml,在我的测试,这是不必要的调试和发布构建。

  onFileSelected = async (file) => {
    // API ref to the server side BE code `addWebServerFilter("/api/uploadtodir", new WebServerFilter()`
    // https://github.com/flyskywhy/react-native-file-server/blob/1034a33dd6d8b0999705927ad78368ca1a639add/android/src/main/java/webserver/WebServer.java#L356
    // could not be 'localhost' but IP address
    const serverUploadApi = 'http://192.168.1.123:8080/api/uploadtodir';

    // the folder on server where file will be uploaded to, could be e.g. '/storage/emulated/0/Download'
    const serverFolder = '/storage/emulated/0/FileServerUpload';

    const fileToUpload = {
      // if want to upload and rename, it can be `name: 'foo.bar'`, but can not be 'foo'
      // only if your server upload code support file name without type, on our server
      // https://github.com/flyskywhy/react-native-file-server/blob/1034a33dd6d8b0999705927ad78368ca1a639add/android/src/main/java/webserver/WebServer.java#L372
      // will cause java.lang.StringIndexOutOfBoundsException in substring()
      name: file.name,

      // type is necessary in Android, it can be 'image/jpeg' or 'foo/bar', but can not be
      // 'foo', 'foo/', '/foo' or undefined, otherwise will cause `[AxiosError: Network Error]`
      type: 'a/b',

      uri: Platform.OS === 'android' ? file.uri : file.uri.replace('file://', ''),
    };

    const form = new FormData();
    form.append('path', serverFolder);
    form.append('uploadfile', fileToUpload);

    // ref to the server side FE code `this.axios.post("/api/uploadtodir", parms, config)`
    // https://github.com/flyskywhy/react-native-file-server/blob/1034a33dd6d8b0999705927ad78368ca1a639add/fileserverwebdoc/src/views/Manage.vue#L411
    let res = await axios.post(serverUploadApi, form, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
      onUploadProgress: function (progressEvent) {
        console.warn(progressEvent);
      },
    });

    // ref to the server side BE code `return newFixedLengthResponse("Suss");`
    // https://github.com/flyskywhy/react-native-file-server/blob/1034a33dd6d8b0999705927ad78368ca1a639add/android/src/main/java/webserver/WebServer.java#L380
    if (res.data === 'Suss') {
      console.warn('Upload Successful');
    } else if (res.data === 'fail') {
      console.warn('Upload Failed');
    }
  };

React-native Expo和Node Express后端也有同样的问题。这个问题是关于模拟器本地主机和服务器本地主机之间的冲突。您的后端服务器可能运行在127.0.0.1:8000上,但模拟器无法找到这一点。

在终端中使用命令“ipconfig”找到您的ipv4地址。例如,它将是192.138.1.40

在此之后,将其放入fetch ('http://192.138.1.40:8080/')。 同样重要的是—使用相同的主机和端口运行后端服务器。 以Node Express为例:

app.listen(8080, () => console.log("服务器正在运行!"))