[英]react ie fetch Unhandled promise rejection TypeError: Network request failed
[英]Unhandled promise rejection: TypeError: Network request failed in expo react native
我正在使用 expo 创建一个 MERN 反应本机移动应用程序,但我坚持如何使用 express 连接 REST API。 下面是代码。
应用程序.js
import React from "react";
import {
StyleSheet,
Text,
View,
TextInput,
TouchableOpacity,
SafeAreaView,
} from "react-native";
class Form extends React.Component {
constructor() {
super();
this.State = {
title: "",
description: "",
};
}
getInput(text, field) {
if (field == "title") {
this.setState({ title: text });
} else if (field == "description") {
this.setState({ description: text });
}
//console.warn(text)
}
submit() {
let collection = {};
(collection.title = this.state.title),
(collection.description = this.state.description);
console.warn(collection);
var url = "http://localhost/3000";
fetch(url, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify({
collection,
}),
});
}
render() {
return (
<SafeAreaView style={styles.container}>
<TextInput
underlineColorAndroid="rgba(0,0,0,0)"
placeholder="Title"
selectionColor="#fff"
keyboardType="default"
onChangeText={(text) => this.getInput(text, "title")}
/>
<TextInput
multiline={true}
numberOfLines={4}
underlineColorAndroid="rgba(0,0,0,0)"
placeholder="Description"
selectionColor="#fff"
keyboardType="default"
onChangeText={(text) => this.getInput(text, "description")}
/>
<TouchableOpacity onPress={() => this.submit()}>
<Text>Submit</Text>
</TouchableOpacity>
</SafeAreaView>
);
}
}
export default Form;
Post.js
const mongoos = require("mongoose");
const PostSchema = mongoos.Schema({
title: {
type: String,
required: true,
},
description: {
type: String,
required: true,
},
date: {
type: Date,
default: Date.now,
},
});
module.exports = mongoos.model("Post", PostSchema); // giving this schma name Post
帖子.js
const express = require("express");
const router = express.Router();
const Post = require("./Post");
//Gets back all the posts
router.get("/", async (req, res) => {
try {
const post = await Post.find();
res.json(post);
}catch (err) {
res.json({ message: err });
}
});
//To Submit the Post
router.post("/", async (req, res) => {
//console.log(req.body);
const post = new Post({
title: req.body.title,
description: req.body.description,
});
try {
const savedPost = await post.save();
res.json(savedPost);
} catch (err) {
res.json({ message: err });
}
});
//Get back specific Post
router.get("/:postId", async (req, res) => {
try {
const post = await Post.findById(req.params.postId);
res.json(post);
} catch (err) {
res.json({ message: err });
}
});
// to delete specific post
router.delete("/:postId", async (req, res) => {
try {
const removePost = await Post.remove({ _id: req.params.postId });
res.json(removePost);
} catch (err) {
res.json({ message: err });
}
});
//update Post
router.patch("/:postId", async (req, res) => {
try {
const updatePost = await Post.updateOne(
{ _id: req.params.postId },
{ $set: { title: req.body.title } }
);
res.json(updatePost);
} catch (err) {
res.json({ message: err });
}
});
module.exports = router;
服务器.js **
const express = require("express");
const app = express();
const mongoos = require("mongoose");
const bodyParser = require("body-parser");
const postRoute = require("./posts");
const url = "mongodb://localhost/REST_API";
app.use(bodyParser.json());
app.use("/post", postRoute);
app.get("/", (req, res) => {
res.send("We are on Home ");
});
// connecting to database
mongoos.connect(url, { useNewUrlParser: true });
const con = mongoos.connection;
con.on("open", () => {
console.log("database connected,,,");
});
app.listen(3000);
以下是我运行时给出的错误。
[未处理的 promise 拒绝:TypeError:网络请求失败] 在 node_modules\whatwg-fetch\dist\fetch.umd.js:535:17 in setTimeout$argument_0 at node_modules\react-native\Libraries\Core\Timers\JSTimers.js: 130:14 在 node_modules\react-native\Libraries\Core\Timers\JSTimers.js 的 _callTimer 中:383:16 在 node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js 的 callTimers 中:416:4 在 node_modules 的 __callFunction react-native\Libraries\BatchedBridge\MessageQueue.js:109:6 in __guard$argument_0 at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:364:10 in __guard at node_modules\react-native\Libraries\BatchedBridge\ MessageQueue.js:108:4 in callFunctionReturnFlushedQueue at [native code]:null in callFunctionReturnFlushedQueue
可能是模拟器/模拟器本地主机和服务器本地主机之间存在冲突,如下面链接的问题中所述。 您可以尝试将 App.js 中的url
变量App.js
为您的 IP 地址。
尝试更改 localhost 而不是使用 localhost 将其替换为解决我的问题的 Ip 地址
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.