我是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;