首页 > 解决方案 > 从 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 并在模拟器上运行它可能会工作吗?

标签: laravelapireact-nativereact-native-androidexpo

解决方案


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


推荐阅读