我正在使用expo创建一个MERN-react原生移动应用程序,但我一直纠结于如何使用express连接REST API。下面是代码。
App.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
posts.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;
server.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);
以下是我运行时给定的错误。
[未处理的承诺拒绝:类型错误:网络请求失败]在setTimeout$argument_0中的node_modules\whatwg fetch\dist\fetch.umd.js:535:17在_callTimer中的node_modules\react native\Libraries\Core\Timers\JSTimers.js:130:14在callTimers中的node_modules\react native\Libraries\Core\Timers\JSTimers.js:383:16在__callFunction中的node_modules\react native\Libraries\BatchedBridge\MessageQueue.js:416:4位于__guard$argument_0中的node_modules\react native\Libraries\BatchedBridge\MessageQueue.js:109:6位于__guard中的node_modules\react native\Libraries\BatchedBridge\MessageQueue.js:364:10在callFunctionReturnFlushedQueue中的node_modules\react native\Libraries\BatchedBridge\MessageQueue.js:108:4在[本机代码]:callFunctionReturnFlushedQueue 中为null
模拟器/模拟器localhost和服务器localhost之间可能存在冲突,如下面链接的问题所述。您可以尝试将App.js
中的url
变量更改为您的IP地址。
未处理的承诺拒绝:类型错误:网络请求失败expo节点后端
[网络错误]:类型错误:网络请求失败
尝试更改localhost而不是使用localhost将其替换为Ip地址解决了我的问题