首页 > 解决方案 > 如何将 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');
});

标签: node.jsreactjsreact-nativeaxiosfetch-api

解决方案


反应本机代码中 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))

    }

推荐阅读