首页 > 解决方案 > 从快速服务器获取数据到 React Native 应用程序的问题

问题描述

我正在尝试开发一个从本地服务器获取数据的 android 应用程序,虽然我没有遇到任何错误,但我没有得到请求的数据。正如标题所说,我将 React-Native 用于我的前端应用程序,并将 Nodejs(expressjs) 用于后端。

(当我使用 cURL 发出获取请求时,它会成功获取数据。我在浏览器上运行应用程序)

我的服务器代码是这样的:

const express = require('express')
const cors = require('cors')

const app = express()

app.use(cors())

app.get('/' , async (req, res) => {

    res.send({"abc" : 123})
});

const PORT = process.env.PORT || 5000 

app.listen(PORT, () => console.log(`server started on port ${PORT}`));

我的前端代码是这样的:

import React, { useEffect, useState } from 'react';
import { ActivityIndicator, Text, View } from 'react-native';

const Sandbox = () => {
  const [isLoading, setLoading] = useState(true);
  const [data, setData] = useState([]);

  const getData = async () => {
     try {
      const response = await fetch('http://localhost:5000/');
      setData(response);
    } catch (error) {
      console.error(error);
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    getData();
  }, []);

  return (
    <View style={{ flex: 1, padding: 24 }}>
      {isLoading ? <ActivityIndicator/> : (
        <Text>{Object.keys(data)}</Text>
      )}
    </View>
  );
};

export default Sandbox

标签: react-nativeexpress

解决方案


试试这个:

  const [isLoading, setLoading] = useState(true);
  const [data, setData] = useState();

  const fetchData = async (url) => {
    const response = await fetch(url);
    return response.json();
  };

  const getData = () => {
    try {
      fetchData("http://localhost:5000/").then((data) => {
        setData(data);
        setLoading(false);
      });
    } catch (error) {
      console.error(error);
    }
  };

推荐阅读