gpt4 book ai didi

mongodb - 如何将 Rest api 与 React Native 结合使用;网络通话问题

转载 作者:行者123 更新时间:2023-12-02 03:46:40 26 4
gpt4 key购买 nike

我是 React Native 的新手,我使用 Mongodb 和 MongoDb atlas 中的快速路由等制作了一个简单的后端。我成功地能够使用Postman在存储标题和描述的mongodb图集上发布/获取/修补/删除操作。一切正常。

问题来了 首先,当我在 ReactNative 中制作一个简单的前端并接受输入标题和描述时。我希望应用程序能够简单输入标题和描述,并在“提交”按钮上将其存储到 mongodb Atlas 中,就像 postman 所做的那样。我尝试过,但它不起作用的代码如下。我不知道如何将前端与后端进行通信。我看了很多教程,但无法理解要点。

其次,当我创建一个在 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

服务器.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,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;

最佳答案

这里有一个非常基本的解决方案来解决您的问题:

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

2:现在前往 Heroku.com 并在那里创建一个应用程序并在那里附加您的卡,以便使用完整的免费沙盒功能

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

4:对于数据通信(又名网络请求),使用 axios 比 Fetch 更容易

最佳实践使用:

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

5:为了在 package json 中运行多个命令,并能够在 package.json 中运行多个脚本,您可以这样做

scripts:{"run": "yarn start" && "react-native-expo"}

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

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

7:我发现您在获取后没有处理 AsyncAwait Try catch 或 Promise

8:您也没有点击服务器端 URL,看起来您正在点击数据库连接 url。你应该做的是点击你的 POST/GET/UPDATE 路由端点

关于mongodb - 如何将 Rest api 与 React Native 结合使用;网络通话问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59173941/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com