TypeError: сбой сетевого запроса - PullRequest
0 голосов
/ 01 октября 2019

У меня есть небольшой проект в школе, который использует React-native. Моя работа - чтение данных в базе данных (localhost) и рендеринг в плоский список. Проблема вроде заголовка, я видел какое-то решение, которое можно исправить на многих страницах, но оно не работает. Это мой код route.js:

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

const connection = mysql.createPool({
  host     : 'localhost',
  user     : 'root',
  password : '',
  database : 'mangareader'
});
const app = express();

// Creating a GET route that returns data from the 'users' table.
app.get('/manga', function (req, res) {
    // Connecting to the database.
    connection.getConnection(function (err, connection) {

    // Executing the MySQL query (select all data from the 'users' table).
    connection.query('SELECT * FROM manga', 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/manga so you can see the data.');
});

И это мой код рендеринга:

import React, {Component} from 'react';
import {
    FlatList,
    StyleSheet,
    View,
    Text,
    ActivityIndicator,
  } from 'react-native'; 


  export default class MangaList extends Component {

    constructor(props){
        super(props);
        this.state ={ isLoading: true}
      }

      componentDidMount(){
        return fetch('192.168.1.5:3000/manga')
          .then((response) => response.json())
          .then((responseJson) => {

            this.setState({
              isLoading: false,
              dataSource: responseJson.manga,
            }, function(){

            });

          })
          .catch((error) =>{
            console.error(error);
          });
      }



      render(){

        if(this.state.isLoading){
          return(
            <View style={{flex: 1, padding: 20}}>
              <ActivityIndicator/>
            </View>
          )
        }

        return(
          <View style={styles.container}>
            <FlatList
              data={this.state.dataSource}
              renderItem={({item}) => <Text>{item.manga_name}, {item.manga_des}</Text>}
              keyExtractor={({id}, index) => manga_id}
            />
          </View>
        );
      }
    }
  const styles = StyleSheet.create({
      container: {
          marginTop: 15,
          flex: 1,
          justifyContent: 'center',
          alignItems: 'center',
          backgroundColor: '#F5FCFF'
      },
  });

Но он работает хорошо, когда я заменяю localhost на https://facebook.github.io/react-native/movies.json. Кстати, мой английский не очень хорош, поэтому, пожалуйста, прости меня, если у меня неправильный синтаксис

1 Ответ

0 голосов
/ 02 октября 2019

Если ваш экспресс-сервер работает нормально:

Если ваш сервер находится на локальном хосте, измените IP-адрес на http://10.0.2.2:3000/manga для доступа к вашему серверу.

Если вы хотите к нему подключитьсядругой хост, или используйте 192.168.*.*, введите adb reverse tcp:3000 tcp:3000 в своем терминале (имея adb в вашем PATH или в том же каталоге) и используйте http://192.168.*.*:3000/manga

Проверьте это тоже: Android 8: HTTP-трафик в незашифрованном виде не разрешен , как предложено moritzw

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...