Mongodb 如何将RESTAPI与React Native一起使用;网络通话问题

Mongodb 如何将RESTAPI与React Native一起使用;网络通话问题,mongodb,react-native,mongodb-atlas,Mongodb,React Native,Mongodb Atlas,我是一个新手, 我使用Mongodb atlas中的Mongodb和express routes等制作了一个简单的后端。我成功地在mongodb atlas上发布/获取/修补/删除操作,使用Postman存储标题和描述。一切正常 当我在ReactNative中创建一个简单的前端时,首先出现了一个问题,它接受输入标题和描述。我希望应用程序能够像邮递员一样,简单地输入标题和描述,并按提交按钮将其存储到mongodb Atlas中。我试过了,但代码如下。我不知道如何将前端通信到后端。我看了很多教程,但

我是一个新手, 我使用Mongodb atlas中的Mongodb和express routes等制作了一个简单的后端。我成功地在mongodb atlas上发布/获取/修补/删除操作,使用Postman存储标题和描述。一切正常

当我在ReactNative中创建一个简单的前端时,首先出现了一个问题,它接受输入标题和描述。我希望应用程序能够像邮递员一样,简单地输入标题和描述,并按提交按钮将其存储到mongodb Atlas中。我试过了,但代码如下。我不知道如何将前端通信到后端。我看了很多教程,但没有抓住要点

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

路由文件夹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('/', 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;  
定义的模式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  
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);
前端表单.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,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,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; 
从“React”导入React;
从“react native”导入{样式表、文本、视图、文本输入、TouchableOpacity};
类形式扩展了React.Component{
构造函数(){
超级();
此。状态={
标题:“”,
说明:“”
} 
}
getInput(文本、字段){
如果(字段=='title')
{ 
this.setState({title:text,})
}
else if(字段=='description')
{
this.setState({description:text,})
}
//控制台。警告(文本)
} 
提交(){
让集合={}
collection.title=this.state.title,
collection.description=this.state.description;
控制台。警告(收集);
var url=process.env.DB_连接;
获取(url{
方法:“POST”,
标题:{
接受:'application/json',
“内容类型”:“应用程序/json”,
},
正文:JSON.stringify({
收集
}),
});
}
render(){
返回(
this.getInput(文本,'title')}
/>
this.getInput(文本“description”)}
/>
this.submit()}style={styles.btn}>
提交
);
}
}  
导出默认表单;

这里有一个非常基本的解决方案:

1:如果您使用的是基于Rest API的通信模型,请在GITHUB上进行两次单独的回购。一个用于React本机应用程序,一个用于服务器端应用程序

2:现在去Heroku.com,在那里制作一个应用程序,并在那里附上你的卡,以便使用完全免费的沙盒功能

3:在那里创建一个项目,并找到从Github部署的选项

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

最佳实践使用:

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

scripts:{"run": "yarn start" && "react-native-expo"}
6:或者如果你的脚本需要在后台持续运行,最好创建两个单独的脚本

scripts:{"run1": "yarn start", "run2":"yarn start2"}
7:我看到您没有在处理AsyncWait Try catch或Promise后获取


8:您也没有点击服务器端URL,似乎您点击的是DB连接URL。你应该做的是点击你的POST/GET/UPDATE路由端点

hie Abdul!我希望你做得很好。我建议使用axios或fetch,以便从应用程序端到Api端进行通信。如需进一步了解,请联系我尝试获取(在我的代码的最后部分)。你能看到我所缺少的吗?我怎样才能同时运行服务器和expo应用程序那个获取调用的响应是什么!您使用的是react nativei中使用DOT_ENV api结构的包,我看您没有使用。在fetchLet-us中命中url端点后,可以使用ASYNC/AWAIT或ThenCatch。这就是工作。哇。。过去两天我一直被困在这里。非常感谢你的帮助。我希望fwd能继续发展heroku和github。作为一个新手,这对我来说是件大事!!你好Abdul Wahab,你能展示一下你是怎么做到的吗。我也有同样的问题,但在查看Rizwan提供的答案后,我仍然收到一个错误,上面写着“[未处理的承诺拒绝:TypeError:网络请求失败]”。