Отклонение необработанного обещания: TypeError: сбой сетевого запроса серверной части узла expo - PullRequest
1 голос
/ 27 мая 2020

У меня есть серверная часть узла, которую запрашивает мое приложение expo. Бэкэнд node- express -mon go работает идеально, что я могу проверить с помощью запроса GET от почтальона, но я получаю необработанное отклонение обещания Ошибка сети в моем приложении

Полная ошибка:

[Unhandled promise rejection: TypeError: Network request failed]
- node_modules/whatwg-fetch/dist/fetch.umd.js:473:29 in xhr.onerror
- node_modules/event-target-shim/dist/event-target-shim.js:818:39 in EventTarget.prototype.dispatchEvent
- node_modules/react-native/Libraries/Network/XMLHttpRequest.js:574:29 in setReadyState
- node_modules/react-native/Libraries/Network/XMLHttpRequest.js:388:25 in __didCompleteResponse
- node_modules/react-native/Libraries/vendor/emitter/EventEmitter.js:190:12 in emit
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:436:47 in __callFunction
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:111:26 in __guard$argument_0
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:384:10 in __guard
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:110:17 in __guard$argument_0
* [native code]:null in callFunctionReturnFlushedQueue

вот мой код:

api. js

export const fetchMeetups = () =>
    fetch('http://localhost:3000/api/meetups')
        .then(res => res.json());

App. js

import * as React from 'react';
import { Platform, StyleSheet, Text, View, ActivityIndicator } from 'react-native';
import { fetchMeetups } from './constants/api'; 

const instructions = Platform.select({
  ios: `Press Cmd+R to reload,\nCmd+D or shake for dev menu`,
  android: `Double tap R on your keyboard to reload,\nShake or press menu button for dev menu`,
});


class App extends React.Component{
  static defaultProps = {
    fetchMeetups
  }

  state = {
    loading: false,
    meetups: []

  }

  async componentDidMount(){
    this.setState({loading: true});
    const data = await this.props.fetchMeetups();
    setTimeout(() => this.setState({loading: false, meetups: data.meetups}),2000)
  }


  render(){
    if(this.state.loading){
      return(
        <ActivityIndicator size="large"/>
      )
    }
    return (
      <View style={styles.container}>
        <Text>MeetupME</Text>
      </View>
    );
  }

}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

индекс. js

import { registerRootComponent } from 'expo';

import App from './App';

// registerRootComponent calls AppRegistry.registerComponent('main', () => App);
// It also ensures that whether you load the app in the Expo client or in a native build,
// the environment is set up appropriately
registerRootComponent(App);

-------------- ОБНОВЛЕНИЕ ----- ------------- добавлен блок catch для извлечения и получения этой новой ошибки

Network request failed
- node_modules/whatwg-fetch/dist/fetch.umd.js:473:29 in xhr.onerror
- node_modules/event-target-shim/dist/event-target-shim.js:818:39 in EventTarget.prototype.dispatchEvent
- node_modules/react-native/Libraries/Network/XMLHttpRequest.js:574:29 in setReadyState
- node_modules/react-native/Libraries/Network/XMLHttpRequest.js:388:25 in __didCompleteResponse
- node_modules/react-native/Libraries/vendor/emitter/EventEmitter.js:190:12 in emit
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:436:47 in __callFunction
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:111:26 in __guard$argument_0
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:384:10 in __guard
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:110:17 in __guard$argument_0
* [native code]:null in callFunctionReturnFlushedQueue

emulator

postman

Ответы [ 2 ]

1 голос
/ 11 июня 2020

Была такая же проблема с React-native Expo и Python Django серверной частью. Проблема в конфликте между локальным хостом эмулятора и локальным хостом сервера. Ваш внутренний сервер может работать на 127.0.0.1:8000, но эмулятор не может этого найти.

В терминале найдите свой IPv4-адрес с помощью команды 'ipconfig'. Например, это будет 192.138.1.40

После этого поместите его в свою выборку ('http://192.138.1.40: 8000 / ').
И что также важно - запустите свой внутренний сервер с тем же хостом и портом.
На python Django например:

py manage. py runserver 192.138.1.40:8000

На Django вам также нужно будет добавить ALLOWED_HOSTS = ['192.138.1.40'] в settings.py

0 голосов
/ 27 мая 2020

вместо localhost в вашем URL-адресе, http://localhost: 3000 / api / meetups , укажите свой IP-адрес, например http://192.168.49.108: 3000 / api / meetups

...