繁体   English   中英

React Native 获取错误:“[未处理的 promise 拒绝:TypeError:网络请求失败]”

[英]React Native fetch error: “[Unhandled promise rejection: TypeError: Network request failed]”

我正在尝试使用fetch function 在本机反应中发出请求。 我正在使用expo 当调用负责发送请求的 function 时,我得到这个错误:

[Unhandled promise rejection: TypeError: Network request failed]
- node_modules\whatwg-fetch\dist\fetch.umd.js:473:29 in xhr.onerror
- node_modules\event-target-shim\dist\event-target-shim.js:818:39 in EventTarget.prototype.dispatchEvent
- node_modules\react-native\Libraries\Network\XMLHttpRequest.js:574:29 in setReadyState
- node_modules\react-native\Libraries\Network\XMLHttpRequest.js:388:25 in __didCompleteResponse
- node_modules\react-native\Libraries\vendor\emitter\EventEmitter.js:190:12 in emit
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:436:47 in __callFunction
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:111:26 in __guard$argument_0
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:384:10 in __guard
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:110:17 in __guard$argument_0
* [native code]:null in callFunctionReturnFlushedQueue

这是我的代码:

import React, { useState } from "react";
import {
  StyleSheet,
  Text,
  View,
  SafeAreaView,
  Modal,
  Alert,
} from "react-native";
import { TextInput, Button } from "react-native-paper";
import * as ImagePicker from "expo-image-picker";
import * as Permissions from "expo-permissions";
const CreateEmployee = () => {
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [phone, setPhone] = useState("");
  const [salary, setSalary] = useState("");
  const [picture, setPicture] = useState("");
  const [position, setPosition] = useState("");
  const [modal, setModal] = useState(false);

  const submitData = () => {
    fetch("http://192.168.1.3:3000/send-data", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(name, email, phone, salary, picture, position),
    })
      .then((res) => res.json())
      .then((data) => console.log(data));
  };

  const runImagePicker = async () => {
    const { granted } = await Permissions.askAsync(Permissions.CAMERA_ROLL);
    if (granted) {
      const data = await ImagePicker.launchImageLibraryAsync({
        mediaTypes: ImagePicker.MediaTypeOptions.Images,
        allowsEditing: true,
        Aspect: [1, 1],
        Quality: 0.5, //From the actual image
      });
      if (!data.cancelled) {
        let newFile = {
          uri: data.uri,
          type: `test/${data.uri.split(".")[1]}`,
          name: `test.${data.uri.split(".")[1]}`,
        };
        handleUpload(newFile);
      }
      console.log("Hola");
    } else {
      alert("You need to permit using the camera");
    }
  };
  const runCamera = async () => {
    const { granted } = await Permissions.askAsync(Permissions.CAMERA);
    if (granted) {
      const data = await ImagePicker.launchCameraAsync({
        mediaTypes: ImagePicker.MediaTypeOptions.Images,
        allowsEditing: true,
        Aspect: [1, 1],
        Quality: 0.5, //From the actual image
      });
      console.log(data);
    } else {
      alert("You need to permit using the camera");
    }
  };

  const handleUpload = (image) => {
    const data = new FormData();
    data.append("file", image);
    data.append("upload_preset", "employeeApp");
    data.append("cloud_name", "omar1");
    fetch("https://api.cloudinary.com/v1_1/omar1/image/upload", {
      method: "post",
      body: data,
    })
      .then((res) => res.json())
      .then((data) => {
        console.log(data);
      });
  };

  return (
    <View style={styles.root}>
      <TextInput
        label="Name"
        // value={name}
        mode="outlined"
        theme={theme}
        style={styles.textInputStyle}
        onChangeText={(text) => setName({ text })}
      />
      <TextInput
        label="Email"
        // value={email}
        mode="outlined"
        theme={theme}
        style={styles.textInputStyle}
        onChangeText={(text) => setEmail({ text })}
      />
      <TextInput
        label="Phone"
        // value={phone}
        mode="outlined"
        theme={theme}
        style={styles.textInputStyle}
        onChangeText={(text) => {
          setPhone({ text });
          console.log(text);
        }}
      />

      <TextInput
        label="Salary"
        // value={salary}
        mode="outlined"
        theme={theme}
        style={styles.textInputStyle}
        onChangeText={(text) => {
          setSalary({ text });
        }}
      />

      <TextInput
        label="Position"
        // value={position}
        mode="outlined"
        theme={theme}
        style={styles.textInputStyle}
        onChangeText={(text) => {
          setPosition({ text });
        }}
      />

      <Modal
        // style={styles.modalStyle}
        visible={modal}
        onDismiss={() => setModal(false)}
        animationType="slide"
        transparent={true}
      >
        <View style={styles.modalView}>
          <Button
            icon="cancel"
            style={{ marginTop: 20 }}
            onPress={() => setModal(false)}
          >
            Cancel
          </Button>
          <View style={styles.btnsModalView}>
            <Button
              mode="contained"
              icon="camera"
              style={styles.btnModal}
              onPress={() => runCamera()}
            >
              Camera
            </Button>

            <Button
              mode="contained"
              icon="image"
              style={styles.btnModal}
              onPress={() => runImagePicker()}
            >
              Gallery
            </Button>
          </View>
        </View>
      </Modal>
      <Button
        icon="upload"
        mode="contained"
        style={styles.btnUploadStyle}
        onPress={() => setModal(true)}
      >
        UPLOAD IMAGE
      </Button>
      <Button
        icon="content-save"
        mode="contained"
        style={styles.btnSaveStyle}
        onPress={() => submitData()}
      >
        SAVE
      </Button>
    </View>
  );
};

这是访问"/send-data"时发生的情况:


app.post("/send-data", (req, res) => {
  const myEmployee = new Employee();

  myEmployee.name = req.body.name;
  myEmployee.email = req.body.email;
  myEmployee.phone = req.body.phone;
  myEmployee.picture = req.body.picture;
  myEmployee.salary = req.body.salary;
  myEmployee.position = req.body.position;

  myEmployee
    .save()
    .then(() => {
      // console.log("Employee added!");
      res.send("Employee added!");
    })
    .catch((err) => {
      res.send("Error: " + err);
    });
});

请注意,我已经通过在同一台机器上的浏览器访问链接"/send-data"来测试添加到数据库。 但是,当在 fetch function 中使用它并尝试从我的手机访问它时,它不起作用。

我尝试使用 PC 的 IP 后跟端口号和链接发出一个简单的获取请求,它在 PC 上工作,而在手机上不起作用(并且它连接到同一个网络)。

我已经在 stackoverflow 和其他网站上查看了这个问题的所有答案,但没有一个对我有用。

你不能从本地服务器获取本地反应,我只是建议使用ngrok 您可以简单地将其安装在您的机器上。 go to your terminal and then run ngrok http 3000 if you have macOS and you install it with homebrew (brew install ngrok), or if you are using Linux or windows, you can open the terminal inside your download directory of ngrok and run ./ngrok http 300然后您将获得本地服务器的 URL 因为它是远程服务器。 然后你可以复制这个 URL 并使用 fetch 发出一个 post 请求(虽然我推荐axios )像这样:

const submitData = () => {
fetch("https://cksgbsc62ba7.ngrok.io/send-data", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify(name, email, phone, salary, picture, position),
})
  .then((res) => res.json())
  .then((data) => console.log(data)); };

Surly 我们将毫无问题地提出您的要求。 您还可以通过访问此链接localhost:4040检查传入的请求。

我希望你一切顺利。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM