我无法使用 Fetch 的方法从 react-native 访问 JSON.server 中的数据 [英] I can't access to data in JSON.server from react-native with use of Fetch's method
问题描述
我使用以下代码创建了一个简单的 JSON.server 项目:npm install JSON-server -g
I have created a simple JSON.server project with the following code:
npm install JSON-server -g
我使用以下代码运行此服务器:JSON-server --watch db.json -p 3001 -d 2000
I run this server with the following code:
JSON-server --watch db.json -p 3001 -d 2000
当我在浏览器中运行此服务器时,它可以工作,但是当我在 React Native 中从该服务器获取数据时,这不起作用.
when I run this server in my browser, it works but when I fetch data from this server in react native, this doesn't work.
用于从 JSON.server 获取数据的 react-native 代码:
my react-native's codes for fetch data from JSON.server:
return fetch(baseUrl + "data")
.then(
response => {
if (response.ok) {
return response;
} else {
//error
}
},
error => {
var errmess = new Error(error.message);
throw errmess;
}
)
.then(response => response.json())
.then(dishes => dispatch(fetchData(data)))
.catch(error => dispatch(dataFailed(error.message)));
fetchData
方法:
export const fetchData = data => ({
data: data
});
更新 1:
这是 baseUrl:
this is baseUrl:
export const baseUrl = "http://192.168.1.8:3001/";
请帮我看看有什么问题.
please help me what is the problem.
推荐答案
我的问题是因为我的 ip4 地址.
正如我之前所说,我试过这个问题,但我的问题没有解决.
我确实找到了从服务器获取数据的方法.
my issue was because of my ip4 address.
as I told before, I have tried this question but my problem has not fixed.
I did find a way to fetch data from the server.
对于那些面临类似问题的人.
For those who are facing similar problem.
步骤:
1) 前往 https://ngrok.com/ 并创建帐户
1) Go https://ngrok.com/ and create account
2) 登录
3) 进入设置 &安装,请按照 1、2 步骤操作.
3) Go to setup & installation, follow 1, 2 steps.
4) 将 ngrok.exe 放在您选择的文件夹中.确保该文件夹位于您的 PATH 环境变量中.
4)Place the ngrok.exe in a folder of your choosing. Make sure the folder is in your PATH environment variable.
5) 按照设置 & 的第 3 步操作安装.
5) Follow step 3 of setup & installation.
6) 打开命令提示符并输入 ngrok http(例如:3005)并回车.您将获得一个 ngrok 网址(例如:转发 http://977ab183.ngrok.io)
6) Open your command prompt and type ngrok http (eg: 3005) and enter. You will get a ngrok url (eg: forwarding http://977ab183.ngrok.io)
7) 将此网址(例如:http://977ab183.ngrok.io/)设为您的应用基地址
7) Make this url (eg: http://977ab183.ngrok.io/) your app baseUrl
8) 打开另一个指向您的应用程序目录的命令提示符并运行您的 json 服务器: json-server --watch db.json -p 3005 -d 2000
8) Open another command prompt pointing to your app directory and run your json server: json-server --watch db.json -p 3005 -d 2000
这篇关于我无法使用 Fetch 的方法从 react-native 访问 JSON.server 中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!