React Native Expo:android 上的网络错误

Hei*_*erg 5 android fetch general-network-error react-native axios

我在我的应用程序中使用 axios。当我打开应用程序后第一次发出发布请求时,它失败并出现以下错误。从第二次开始,它就可以正常工作了。

Network Error
- node_modules/axios/lib/core/createError.js:15:17 in createError
- node_modules/axios/lib/adapters/xhr.js:81:22 in handleError
- node_modules/event-target-shim/dist/event-target-shim.js:818:20 in EventTarget.prototype.dispatchEvent
- node_modules/react-native/Libraries/Network/XMLHttpRequest.js:600:10 in setReadyState
- node_modules/react-native/Libraries/Network/XMLHttpRequest.js:395:6 in __didCompleteResponse
- node_modules/react-native/Libraries/vendor/emitter/EventEmitter.js:189:10 in emit
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:416:4 in __callFunction
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:109:6 in __guard$argument_0
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:364:10 in __guard
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:108:4 in callFunctionReturnFlushedQueue
* [native code]:null in callFunctionReturnFlushedQueue
Run Code Online (Sandbox Code Playgroud)

我正在真实的 Android 设备上运行,通过 http://my_ip:my_port/ 连接到真实的服务器。我尝试在 kotlin 中创建一个 Native android 项目,并且它运行正常,没有任何问题

这是我的代码:

const upload = () => {
    setAnalyzing(true);

    axios.post(URL_PREDICT, formBody(), {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    }).then(handleSuccess)
      .catch(handleFail);
  }

  const formBody = () => {
    const photo = {
      uri: image,
      type: 'image/jpeg',
      name: 'photo.jpg',
    };
    const form = new FormData();
    form.append("file", photo);
    return form;
  };

  const handleFail = (error) => {
    console.log(error)
    console.log(error?.response?.data);
    setAnalyzing(false);
    toggle();
    alert("ERROR " + error);
  };

  const handleSuccess = response => {
    console.log('success...');
    setAnalyzing(false);
    toggle();
    console.log(response);
    navigation.navigate('Result', response);
  };
Run Code Online (Sandbox Code Playgroud)

知道是什么原因造成的吗?

Muh*_*man 10

解决方案1

确保您的 URL 地址中包含“http://”

  1. 从localhost更改为您的ip
  2. 添加http://

http://192.168.43.49:3000/用户/

解决方案2

我遇到了同样的问题,它发生在 Android 中,但在 IOS 中运行良好。我猜这个问题是关于 Flipper Network 的。

有一段时间,我评论了

initializeFlipper(this, getReactNativeHost().getReactInstanceManager())

在这个文件中 /android/app/src/main/java/com/{your_project}/MainApplication.java

解决方案3

谁还在为这个问题苦苦挣扎。这是因为 Flipper 网络插件而发生的。我禁用了它,一切正常。

我的解决方法是注释掉第 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);
Run Code Online (Sandbox Code Playgroud)

在这个文件中android/app/src/debug/java/com/**/ReactNativeFlipper.java

解决方案4

不需要添加Access-Control-Expose-Headers.

需要这个:

                headers:{
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'Accept': 'application/json'}
            }
Run Code Online (Sandbox Code Playgroud)

我调整了你的服务器,它可以工作。

  • 将 localhost 更改为 IP 地址对我有用! (2认同)

gmj*_*gmj 8

我认为你正在使用expo-image-picker.

\n

这里有两个独立的问题在起作用。让\xe2\x80\x99s 说我们imageUriimage-picker获取,然后我们将使用以下代码行从前端上传。

\n
const formData = new FormData();\nformData.append(\'image\', {\n uri : imageUri,\n type: "image",\n name: imageUri.split("/").pop()\n});\n
Run Code Online (Sandbox Code Playgroud)\n

第一个问题是其imageUri本身。如果让\xe2\x80\x99s 说照片路径是/user/.../path/to/file.jpg. 然后 android 中的文件选择器将给出imageUri值,而file:/user/.../path/to/file.jpgiOS 中的文件选择器将给出imageUrifile:///user/.../path/to/file.jpg.

\n

第一个问题的解决方案是使用file://而不是file:formData。

\n

第二个问题是我们没有使用正确的方法mime-type. 它在 iOS 上运行良好,但在 Android 上则不行。更糟糕的是文件选择器包给出的文件类型为 \xe2\x80\x9cimage\xe2\x80\x9d 并且它没有给出正确的 mime 类型。

\n

mime-type解决办法是在formData中使用正确的字段类型。例如:.jpg文件的 mime 类型为 ,文件的 mimeimage/jpeg类型为。我们不必手动执行此操作。相反,您可以使用一个非常著名的 npm 包,称为mime.pngimage/png

\n

最终的工作解决方案是:

\n
import mime from "mime";\n\nconst newImageUri =  "file:///" + imageUri.split("file:/").join("");\n\nconst formData = new FormData();\nformData.append(\'image\', {\n uri : newImageUri,\n type: mime.getType(newImageUri),\n name: newImageUri.split("/").pop()\n});\n
Run Code Online (Sandbox Code Playgroud)\n