首页 > 解决方案 > React Native 获取本地 API

问题描述

我有一个 expo react 本机应用程序,我想在另一个项目中使用我制作的 API 中的一个函数。我在 Postman 中测试了 url,并且 url 工作正常。但我得到了错误:Network error failed在应用程序中。

klt_idand来自klt_nameClients 表。url 指向一个函数,该函数显示 Clients 表中的所有记录。

这就是我现在所拥有的:

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

  componentDidMount(){
    return fetch('http://127.0.0.1:8000/api/v2/klant', )
      .then((response) => response.json())
      .then((responseJson) => {
        console.log(responseJson)
        this.setState({
          isLoading: false,
          dataSource: responseJson.data,
        }, function(){

        });

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


  render(){

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

    return(
      <View style={{flex: 1, paddingTop:20}}>
        <FlatList
          data={this.state.dataSource}
          renderItem={({item}) => <Text>{item.klt_id}, {item.klt_name}</Text>}
          keyExtractor={({id}, index) => id}
        />
      </View>
    );
  }
}

提前致谢!

标签: apireact-nativeexpo

解决方案


您可以ngrok试一试:它将允许您拥有一个“正常”的 HTTPS URL,您应该可以在您的 Expo 应用程序中使用而不会出现任何问题。他们网站上的例子:

在此处输入图像描述


推荐阅读