首页 > 解决方案 > 如何将 React Native 与 mySQL 集成

问题描述

我是 React Native 的新手,我正在尝试将我的应用程序与位于我的托管服务提供商 (digitalocean.com) 内的 mySQL 数据库集成。我已经设法通过 nodejs 和 express 获取数据,但它实际上是在获取我的问题所在的数据。

这是怎么回事:

我创建了一个 routes.js 并插入了以下内容:

注意:以下凭据是真实的,但仅用于纯测试,我不介意分享。

const express = require('express');
const bodyParser = require('body-parser');
const mysql = require('mysql');

const connection = mysql.createConnection({
    host: '134.122.22.176',
    user: 'yannb_9',
    password: 'yannb_9',
    database: 'tiomanGrow'
});

// Starting our app.
const app = express();

connection.connect((err) => {
    if (err) {
        console.log('Connection error message: ' + err.message);
        return;
    }
    console.log('Connected!')
    // Creating a GET route that returns data from the 'users' table.
    app.get('/', function (req, res) {
        // Connecting to the database.
        // Executing the MySQL query (select all data from the 'users' table).
        connection.query('SELECT * FROM farmers', function (error, results, fields) {
            // If some error occurs, we throw an error.
            if (error) throw error;
            // Getting the 'response' from the database and sending it to our route. This is were the data is.
            res.send(results)
        });
    });
});

// Starting our server.
app.listen(3000, () => {

    console.log('Go to http://localhost:3000/farmers so you can see the data.');
});

到目前为止一切都很好!您可以单击http://localhost:3000/farmers,运行文件时会看到数据。

这就是我卡住的地方:我要在我的应用程序上显示数据,但我不知道该怎么做。我做了一些研究,看到了一个可能的解决方案,但它不起作用。它实际上给了我一个“网络请求失败”

import React from "react";
import { View, Text, StyleSheet, TextInput, TouchableOpacity } from "react-native";
import { HeaderImg } from '../components/HeaderImg';
import { Button } from '../components/Button';

export default class DB extends React.Component {
    state = {
        email: "",
        password: "",
        errorMessage: null
    };

    fetchData = async() => {
        fetch('http://134.122.22.176:3000/farmers')
        .then(response => response.json())
        .then(users => console.dir(users))
        .catch(error=> console.log(error))
    }


    render() {
        return (
        <View style={styles.container}>
            <HeaderImg />

            <View style={styles.errorMessage}>
            {this.state.errorMessage && (
                <Text style={styles.error}>{this.state.errorMessage}</Text>
            )}
            </View>
            <Button 
            onPress={this.fetchData}
            />
        </View>
        );
    }
}
const styles = StyleSheet.create({      
});

有什么建议么?

标签: mysqlnode.jsreact-native

解决方案


您的 routes.js 文件中 MySQL 数据库的主机名显示为 134.122.22.176。那是数据库IP地址。你不能 fetch从这个 IP 地址。MySQL 数据库不响应标准 HTTP 请求;它们不是网络服务器。

您的 Express 应用程序在localhost上运行:http://localhost:3000/farmers - 例如,我猜您可以在 Web 浏览器中浏览该 URL 并查看数据。如果该 Express 应用程序正在您的开发计算机上运行,​​那么您只需要找出 LAN 上该计算机的 IP 地址 (xx.xx.xx.xx),然后在您的fetch.


推荐阅读