如何在 React Native 中使用 Rest api;网络通话问题
How to Use Rest api with React Native; Network Call Issues
我是 React Native 的新手,
我在 MongoDb 地图集中使用 Mongodb 和快速路线等制作了一个简单的 back-end。我成功地能够使用 Postman 在 mongodb 存储标题和描述的图集上进行 post/get/patch/Delete 操作。一切正常。
问题来了首先,当我在 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);
前端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 本机应用程序,一个用于您的服务器端。
2:现在去 Heroku.com 并在那里制作一个应用程序并在那里附加您的卡以便使用完整的免费沙盒功能
3:在那里创建一个项目并找到一个选项来从 Github 部署。
4:对于数据通信,也就是网络请求,它易于使用 axios 而不是 Fetch
最佳实践使用:
https://riptutorial.com/react-native/topic/857/getting-started-with-react-native
5: 为了 运行 包 json 中的多个命令能够 运行 package.json[=37= 中的多个脚本] 你可以这样做
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 路由端点
我是 React Native 的新手, 我在 MongoDb 地图集中使用 Mongodb 和快速路线等制作了一个简单的 back-end。我成功地能够使用 Postman 在 mongodb 存储标题和描述的图集上进行 post/get/patch/Delete 操作。一切正常。
问题来了首先,当我在 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);
前端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 本机应用程序,一个用于您的服务器端。
2:现在去 Heroku.com 并在那里制作一个应用程序并在那里附加您的卡以便使用完整的免费沙盒功能
3:在那里创建一个项目并找到一个选项来从 Github 部署。
4:对于数据通信,也就是网络请求,它易于使用 axios 而不是 Fetch
最佳实践使用:
https://riptutorial.com/react-native/topic/857/getting-started-with-react-native
5: 为了 运行 包 json 中的多个命令能够 运行 package.json[=37= 中的多个脚本] 你可以这样做
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 路由端点