如何在React Native中使用Rest api;网络通话问题

我是React Native的新手, 我使用Mongodb创建了一个简单的后端,并在MongoDb地图集中表达了路线等。我可以使用 Postman 在存储标题和描述的mongodb地图集上成功发布/获取/补丁/删除操作。一切正常。

问题来了首先,当我在ReactNative中创建一个简单的前端时,该前端需要输入Title和Description。我希望应用程序只需输入标题和描述,并在 Submit 按钮上像邮递员一样将其存储到mongodb Atlas中。我试过了,但是下面的代码不起作用。我不知道如何将前端传达到后端。我看了很多教程,但无法理解这一点。

其次,当我制作服务器时,我在pakage.json>“ start”:“ nodemone server.js”中编写了代码,我需要运行ReactNative应用程序,我更新了pakage.json>“ start “:” expo start“来运行应用程序。 如何如何同时运行服务器和博览会应用程序?如果我分开应用程序文件夹,那么我怎么能连接他们两个。 下面是我的代码。

路由文件夹post.js

const express = require( 'express' );
const router = express.Router();
const Post = require ('../models/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('/',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',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',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',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;  

定义的架构Post.js

const mongoos = require( 'mongoose' );

const PostSchema = mongoos.Schema ({
    title: {
        type: String,required: true
    },description: {
        type: String,date: {
        type: Date,default: Date.now 
    }
})

module.exports = mongoos.model ('Post',PostSchema); // giving this schma name Post  

server.js

const express = require( 'express' );
const app = express();
var mongo = require('mongodb');
const mongoos = require( 'mongoose' );
const bodyParser = require('body-parser');
require('dotenv/config');
const postRoute = require('./Routes/post');

app.use(bodyParser.json());
app.use ('/post',postRoute);

app.get ( '/',(req,res) =>{
  res.send('We are on Home ')
});


// connecting to database
mongoos.connect(
  process.env.DB_CONNECTION,{ useNewUrlParser: true },() => console.log('Connected to db')
);

app.listen(3000);

前端Form.js

import React from 'react';
import { StyleSheet,Text,View,TextInput,TouchableOpacity } 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 = process.env.DB_CONNECTION ;
        fetch(url,{
            method: 'POST',headers: {
                accept: 'application/json','Content-Type': 'application/json',},body: JSON.stringify({
                collection
            }),});
    }

    render() {
      return (
        <View style={styles.container}> 

            <TextInput style={styles.inputBox} 
              underlineColorAndroid= 'rgba(0,0)'
              placeholder='Title'
              selectionColor="#fff" 
              keyboardType="default"
              onChangeText = {(text) => this.getInput(text,'title')}
            />

            <TextInput style={styles.inputBox} 
              multiline = {true}
              numberOfLines = {4}
              underlineColorAndroid= 'rgba(0,0)'
              placeholder='Description'
              selectionColor="#fff" 
              keyboardType="default"
              onChangeText= {(text) => this.getInput(text,'description')}
            />

            <TouchableOpacity onPress={()=>this.submit()} style={styles.btn} >
                <Text style={{textAlign: 'center'}}>Submit</Text>
            </TouchableOpacity>

        </View>
    );
    }
}  

export default Form; 
tianyingqi020 回答:如何在React Native中使用Rest api;网络通话问题

以下是您问题的非常基本的解决方案:

1:如果您使用的是基于Rest API的通信模型,请在 GITHUB 上选择两个单独的存储库。一个用于您的React本机应用程序,另一个用于您的服务器端

2:现在访问Heroku.com并在其中创建一个应用程序并在其中附加卡,以使用完整的免费沙盒功能

3:在此处创建一个项目,然后找到从Github进行部署的选项。

4:对于数据通信,aka网络要求其易于使用的axios而不是Fetch

使用最佳做法:

https://riptutorial.com/react-native/topic/857/getting-started-with-react-native

5:为了在json包中运行多个命令以能够在 package.json 中运行多个脚本,您可以像

一样执行
scripts:{"run": "yarn start" && "react-native-expo"}

6:或者,如果您的脚本需要在后台连续运行,则最好创建两个单独的脚本

scripts:{"run1": "yarn start","run2":"yarn start2"}

7:我看到您没有处理AsyncAwait在获取后尝试catch或Promise

8:您似乎也没有在访问服务器端URL,而是在在访问数据库连接URL。您应该做的是点击您的POST / GET / UPDATE路由端点

本文链接:https://www.f2er.com/2978963.html

大家都在问