react-native - 从快速服务器获取数据到 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
解决方案
试试这个:
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);
}
};
推荐阅读
- javascript - 如何将所有命名的 HTML 标记拉入一个数组?
- c++ - 在 Rcpp-Function 中使用 Bool-Vector 进行子集化(Rcpp Beginner 的问题......)
- image - 从 Shell 脚本运行容器后,将端口公开给 localhost url
- csv - 来自文件名的子集
- python - 删除以相同单词开头的列表项
- powershell - Visual Studio Online 构建和发布 Azure Powershell
- c# - 对 URL 的远程 WebDriver 服务器的 HTTP 请求 - Chrome
- python - 如何对 NumPy 数组应用上下阈值?
- xcode - undefined 不是 React-Native CameraRoll 的对象 RCTCameraRollManager
- java - 无法为 org.gradle.api.Project 类型的项目“:app”上的参数找到方法 buildTypes()