简体   繁体   中英

Unhandled promise rejection: TypeError: Network request failed in expo react native

I am creating a MERN react native mobile apps using expo but I am stuck on how to connect the REST API using express. Below are the code.

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);

Below is the given error whenever I run it.

[Unhandled promise rejection: TypeError: Network request failed] at 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 in _callTimer at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:383:16 in callTimers at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:416:4 in __callFunction at node_modules\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

It might be that there is a conflict between the emulator/simulator localhost and the server localhost, as explained in the questions linked below. You could try changing the url variable in App.js to your IP address.

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

[Network error]: TypeError: Network request failed

try to change localhost instead of using localhost replace it with the Ip address that solved my problem

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM