简体   繁体   中英

Connecting react native to nodejs back end

Am trying to make a simple react native app that fetches the data from my express (nodejs app) and just simply show case it. the app works fine with api links I used from the web but for some reason when I use my own local server ( my own nodejs app) it doesn't show anything.

Am new to react native so I need your help.

This the code of my App.js ( from react native ):

import React, { Component } from "react";
import { Platform, StyleSheet, Text, View, FlatList } from "react-native";
export default class App extends Component<Props> {
  state = {
    data: [],
  };

  fetchData = async () => {
    const response = await fetch("http://myipadress:5001/articles");
    const articles = await response.json();
    this.setState({ data: articles });
  };
  componentDidMount() {
    this.fetchData();
  }
  render() {
    return (
      <View>
        <Text>data</Text>

        <FlatList
          data={this.state.data}
          keyExtractor={(item, index) => index.toString()}
          renderItem={({ item }) => (
            <View
              style={{ backgroundColor: "#abc123", padding: 10, margin: 10 }}
            >
              <Text style={{ color: "#fff", fontWeight: "bold" }}>
                {item.title}
              </Text>

              <Text>{item.genre}</Text>
            </View>
          )}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "#F5FCFF",
  },
});

and this is my api: that i access from the link http://myipadress:5001/articles :

[
    {
        "featured_media": {
            "source_url": "String",
            "caption": "String",
            "media_type": "String"
        },
        "categories": [
            "String"
        ],
        "tags": [
            "String"
        ],
        "_id": "5ea02d3d12d8153e34f779ca",
        "date": "2020-04-22T11:40:45.000Z",
        "title": "String",
        "excerpt": "String",
        "author": "String",
        "link": "String",
        "published_at": "2020-04-22T11:40:45.000Z",
        "content": "String",
        "__v": 0
    }
]

React native doesn't work with the same environment on local machine. You can try this code or axios. But as far as I know it doesn't work in the same local environment.

async () => {
    await fetch('http://myipadress:5001/articles')
    .then((response) => response.json())
    .then((responseJson) => console.log(responseJson))
    .catch(err => console.log(err);

}

I believe the problem here is that you are trying to fetch from an HTTP endpoint which is your local server here. I used to have this problem when I was developing an app with Expo SDK. You can fix this by installing ngrok which will expose an HTTPS endpoint for your local server.

Download ngrok and run ngrok http 5001 or your port number on your terminal. ngrok will expose a HTTPS endpoint which you can use to fetch data.

fetchData = async () => {
    const response = await fetch("replace-with-new-ng-rk-url/articles");
    const articles = await response.json();
    this.setState({ data: articles });
  };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM