首页 > 解决方案 > 如何在 Expo 上使用全局变量调用 API_URL

问题描述

我正在尝试在 Expo 示例中使用 IP 地址进行调用 api,例如 react native 上的登录功能

 UserLoginFunction = () =>
  { 
    const {UserEmail} = this.state;
    const {Password} = this.state;
    if (!UserEmail.trim()) {
      this.setState ({showError: this.state.UserEmail === ""})
      return;
    }
    if (!Password.trim()) {
      this.setState ({showError: this.state.Password === ""})
      return;
    }

    var api = "http://192.168.43.123/Api/login.php?email=" + UserEmail + "&password=" + Password;
    console.log(api);
    return fetch(api)
    .then((response) => response.json())
    .then((responseJson) => {
     /*console.log(responseJson.message);*/
      if(responseJson.status === true)
      {
        console.log(UserEmail);
        this.props.navigation.navigate('HomeScreen', { UserEmail : UserEmail });
      }
      else 
      {
        alert(responseJson.message)
      }
   
       }).catch((error) => {
         console.error(error);
       });
    
   }

我想制作全局变量,特别是像我的 PHP 这样的 IP 地址

public function linkUrl()
    {
        $value = "http://192.168.43.123/";

        return $value;
    }

是否可以?我正在寻找这个来提高效率,所以只有 1 个 IP 地址可以使用声明 API_URL 或 URL 调用任何建议?谢谢你

标签: expoglobal-variables

解决方案


您需要手动设置 BASE_URL。

//config.js
export const BASE_URL = "http://192.168.43.123";

//in your js
import * as config from 'config.js';
...
    fetch( config.BASE_URL+ '/path/to/your/api' )
...

我还建议您使用 axios 而不是 fetch。然后你可以全局设置base_url


推荐阅读