反应本机获取错误:"[Unhandled promise rejection: TypeError: Network request failed]"



我正试图使用fetch函数在react native中发出请求。我正在使用expo。当负责发送请求的函数被调用时,我得到了这个错误:

[Unhandled promise rejection: TypeError: Network request failed]
- node_moduleswhatwg-fetchdistfetch.umd.js:473:29 in xhr.onerror
- node_modulesevent-target-shimdistevent-target-shim.js:818:39 in EventTarget.prototype.dispatchEvent
- node_modulesreact-nativeLibrariesNetworkXMLHttpRequest.js:574:29 in setReadyState
- node_modulesreact-nativeLibrariesNetworkXMLHttpRequest.js:388:25 in __didCompleteResponse
- node_modulesreact-nativeLibrariesvendoremitterEventEmitter.js:190:12 in emit
- node_modulesreact-nativeLibrariesBatchedBridgeMessageQueue.js:436:47 in __callFunction
- node_modulesreact-nativeLibrariesBatchedBridgeMessageQueue.js:111:26 in __guard$argument_0
- node_modulesreact-nativeLibrariesBatchedBridgeMessageQueue.js:384:10 in __guard
- node_modulesreact-nativeLibrariesBatchedBridgeMessageQueue.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功能中使用它并试图从我的手机访问它时,它不起作用。

我试着用电脑的IP,然后是端口号和链接,发出一个简单的get请求,它在电脑上工作,而在手机上不工作(它连接到同一个网络(。

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

您无法在react native中从本地服务器获取,我只建议使用ngrok。你可以简单地将它安装在你的机器上。去你的终点站然后跑步ngrok http 3000如果你有macOS,并且你用自制软件安装它(brew install ngrok(,或者如果你使用的是Linux或windows,你可以打开ngrok下载目录中的终端并运行./ngrok http 300,然后你会得到本地服务器的URL,因为它是远程服务器。然后你可以复制这个URL,并用fetch发出帖子请求(我建议使用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)); };

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

我希望你一切顺利。

相关内容

最新更新