node.js - 如何将 React Native 组件与 Node js 服务器连接起来?(React Native、NodeJS(没有 Express)、MongoDB)
问题描述
我正在创建一个简单的 React Native 应用程序,使用...(React Native 作为前端,Node js 作为服务器(没有 Express 框架)MongoDB Local 中的数据库),所以我为应用程序、Server.js 和 React Native 组件创建了后端在 CreateUser.js
我的问题是, 当我单击提交存储数据的按钮时,我得到一个错误并且是 TypeError(网络请求失败),我也尝试使用不同的 IP 地址调用 API,
所以请帮助我如何将 React Native 与 NodeJS 连接起来,
CreateUser.js(前端)
import React from 'react';
import { StyleSheet,
Text,
View,
TextInput,
TouchableOpacity
} from 'react-native';
class CreateUser extends React.Component {
constructor(){
super();
this.state ={
name:'',
email:'',
mobile:''
}
}
updateValue(text, field){
if(field == 'name'){
this.setState({
name:text,
})
}
else if(field == 'email'){
this.setState({
email:text,
})
}
else if(field == 'mobile'){
this.setState({
mobile:text
})
}
console.log(text);
}
submit(){
let collection = {}
collection.name=this.state.name,
collection.email=this.state.email,
collection.mobile=this.state.mobile
console.warn(collection);
console.log("submit btn pressed and collection is", collection);
// fetch code
var url = 'http://localhost:3005/save';
console.log("collections is that ===== ",collection)
fetch('url', {
method: 'post',
headers:{
'Content-Type': 'application/json',
'Accept':'application/json'
},
body: JSON.stringify(collection),
}).then(res => res.json())
.catch(error => console.error('Error:', error))
.then(res => console.log('Success',res))
}
render(){
const {name, email, mobile} = this.state
return (
<View style={styles.container}>
<Text style={styles.header}>Insert User</Text>
<TextInput
placeholder="Enter Name"
style={styles.textinput}
onChangeText={(text) => this.updateValue(text, 'name')}
></TextInput>
<TextInput
placeholder="Enter Email"
style={styles.textinput}
onChangeText={(text) => this.updateValue(text, 'email')}
></TextInput>
<TextInput
placeholder="Enter Mobile"
style={styles.textinput}
onChangeText={(text) => this.updateValue(text, 'mobile')}
></TextInput>
<TouchableOpacity
style={styles.btn}
onPress={() => this.submit()}
>
<Text >Submit</Text>
</TouchableOpacity>
</View>
);
}
}
const styles = StyleSheet.create({
regform:{
alignSelf:'stretch',
},
header:{
fontSize:24,
color:'#000',
paddingBottom:10,
marginBottom:20,
borderBottomColor:'#199187',
borderBottomWidth:1,
},
textinput:{
alignItems:'stretch',
height:40,
marginVertical:10,
marginHorizontal:10,
marginBottom:20,
color:'black',
borderBottomColor:'gray',
borderBottomWidth:2,
},
btn:{
alignSelf:'stretch',
alignItems:'center',
backgroundColor:'#59cbbd',
padding:20,
marginTop:30,
},
btntext:{
color:'#000',
fontWeight:'bold',
},
});
export default CreateUser;
server.js(后端)
// http module Node server
const { json } = require("body-parser");
const http = require("http");
const { parse } = require('querystring');
const app = http.createServer((req,res) =>{
const url = require('url');
const bodyParser = require('body-parser')
const mongoose = require('mongoose');
const User = require('./User');
var jsonParser = bodyParser.json();
const path = req.url;
console.log(req.url);
if(req.url ==="/save" && req.method == 'POST' ){
console.log("inside save API ") ;
let body = '';
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', () => {
console.log(
parse(body)
);
res.end(body);
});
var MongoClient = require('mongodb').MongoClient;
var urlm = "mongodb://localhost:27017/userdb";
MongoClient.connect(urlm, function(err, db) {
if (err) throw err;
var dbo = db.db("userdb");
var jsonObj = JSON.parse(body);
var myobj = {body};
console.log("Post Data BODY is ",jsonObj);
dbo.collection("users").insertOne(jsonObj, function(err, res) {
if (err) throw err;
console.log("1 record inserted");
db.close();
});
});
}
}).listen(3005,()=>{
console.log('server is running on 3005 port');
});
解决方案
反应本机代码中 fetch 函数中的 url 参数是变量而不是字符串,它的 url 不是“url”
fetch(url, {
method: 'post',
headers:{
'Content-Type': 'application/json',
'Accept':'application/json'
},
body: JSON.stringify(collection),
}).then(res => res.json())
.catch(error => console.error('Error:', error))
.then(res => console.log('Success',res))
}
推荐阅读
- javascript - 如何通过使用 JavaScript 函数单击按钮来返回系统日期?
- c# - 如何通过 C# 或直接从数据库中从 SQL Server 查询的结果中插入批量记录到 SQLite 表中
- javascript - 如何在javascript中的querySelector()的标签中包含输入?
- ios - Objective-c 中的推送通知
- dojo - 使用 Intern.js 进行功能测试:getVisibleText() 不适用于 dijits
- vapor - 在命令中访问数据库
- javascript - 如何使用 javascript 读取 txt 文件并将内容复制到谷歌电子表格文件中
- python - 获取“GLib-GIO-Message:使用‘内存’GSettings 后端。您的设置将不会被保存或与其他应用程序共享。” 蟒蛇错误
- office-js - Office.context.ui.messageParent 在第二次打开对话框时失败
- javascript - ES6:有没有办法在一个语句中导入和赋值?