簡體   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