未处理的承诺拒绝:TypeError:网络请求在 expo react native

时间:2021-03-29 06:50:39

标签: reactjs react-native rest express expo

我正在使用 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);
<块引用>

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

[未处理的承诺拒绝:类型错误:网络请求失败] 在 node_modules\whatwg-fetch\dist\fetch.umd.js:535:17 在 setTimeout$argument_0 在 node_modules\react-native\Libraries\Core\Timers\JSTimers.js:130:14 在 _callTimer 在 node_modules\react-native\Libraries\Core\Timers\JSTimers.js:383:16 in callTimers 在 __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 在 node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:108:4 在 callFunctionReturnFlushedQueue at [native code]:null in callFunctionReturnFlushedQueue

2 个答案:

答案 0 :(得分:1)

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

Unhandled promise rejection: TypeError: Network request failed expo node backend

[Network error]: TypeError: Network request failed

答案 1 :(得分:0)

尝试更改 localhost 而不是使用 localhost 将其替换为 Ip 地址 解决了我的问题