未处理的承诺拒绝:类型错误:网络请求在展会反应本机中失败

San*_*ing 5 rest express reactjs react-native expo

我正在使用 expo 创建 MERN React 本机移动应用程序,但我对如何使用 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;
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

帖子.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;
Run Code Online (Sandbox Code Playgroud)

服务器.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);
Run Code Online (Sandbox Code Playgroud)

以下是我运行时出现的错误。

[未处理的承诺拒绝:TypeError:网络请求失败]在node_modules\whatwg-fetch\dist\fetch.umd.js:535:17在setTimeout$argument_0在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 的 callTimer 中:416:4 在 node_modules\ 的 __callFunction 中在node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js 的__guard$argument_0 中react-native\Libraries\BatchedBridge\MessageQueue.js:109:6:364:10 在node_modules\react-native\Libraries\BatchedBridge\ 的__guard 中MessageQueue.js:108:4 in callFunctionReturnFlushedQueue at [native code]:null in callFunctionReturnFlushedQueue

小智 4

模拟器/模拟器本地主机和服务器本地主机之间可能存在冲突,如下面链接的问题中所述。您可以尝试将url变量更改App.js为您的 IP 地址。

未处理的承诺拒绝:TypeError:网络请求失败 expo 节点后端

[网络错误]:TypeError:网络请求失败