expo - 如何在 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 调用任何建议?谢谢你
解决方案
您需要手动设置 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
推荐阅读
- angular - 是否可以从入口组件访问服务
- javascript - 如何在下一个请求的端点(邮递员)中传递第一个 JSON 响应
- c# - 如何使用块在 sqlLite 中存储巨大的 API 响应(JSON)
- angular - Angular - 延迟加载后在孩子中定义父路由
- javascript - 页面加载后开始转换
- scala - 用另一个替换列表元素并返回新列表
- python - python: from an existing dataframe, convert epoch to readable timestamp and add to a new column
- python - 绘制分布子图
- asp.net - 在 Angular 7 中正确显示模态屏幕
- python - 如何使用python监控从浏览器下载的文件