laravel - 从 laravel API 获取数据以响应本机应用程序(使用 expo 创建)
问题描述
我使用expo创建了一个react native应用程序,并且我正在使用expo 应用程序或 USB 电缆在android设备上运行它,此外还有一个laravel APi,我使用它来测试在实施身份验证之前是否一切正常,事情是我总是收到错误消息(我在 fetch 函数中定义它),我说可能是因为 URL 但当我在网络上尝试它时它工作正常!我希望这个解释清楚!我需要帮助才能从 laravel api 获取数据到 react native 应用程序!
反应原生:
构造函数代码:
constructor(props) {
super(props);
this.state = {
email: "",
password: "",
};
}
这是获取功能:
_onLoginPressed = () => {
fetch("http://127.0.0.1:8000/api/indexp", {
method: "GET",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
Alert.alert("logged");
})
.catch((error) => {
console.log('erroc message');
});
};
世博会在这个地址(局域网)运行:exp://192.168.1.4:19000
拉拉维尔:
在 api.php
Route::get('indexp','PostsController@indexp');
在 PostsController 中:
public function indexp()
{
$post = Post::all();
return response()->json($post);
}
如果我安装 android studio 并在模拟器上运行它可能会工作吗?
解决方案
Your problem is at the fetch request. You need to access the IP of the API server, in this case the LAN address of your PC (run ifconfig on linux or ipconfig in windows). Then you have to start your webserver with that IP as host, and set a port if you want, i.e. php artisan serve --host 192.168.10.100 --port 8000, where the IP is the IP of your PC and the port is the one you like.
Then on your fetch request you have to go the http://192.168.10.100:8000/api/indexp and get the results from there. I would recommend not getting the IP and port on each file, but putting them on a config file so if you need to change them you just change in one place
推荐阅读
- android - PreviewView 准备好时如何获取 CameraX 事件
- python - 将 JSON 元素附加到列表
- c# - 使用 HttpClient 发送原始 HTTP 数据包
- c# - 执行插件时出现 System.MethodAccessException(Dynamics 365 在线)
- python - python请求输出中的错误编码(?)
- vue.js - 清单:行:1,列:1,语法错误。清单的公共链接已更改
- sql - SQL 参数化排序
- javascript - VSCode 停止连接到 MongoDB 服务器 - NodeJS
- flutter - 我正在尝试制作一个与极客教程作为参考的极客应用程序。我有以下错误
- matplotlib - geopandas 在使用 xlim、ylim 时控制图例大小