【发布时间】:2016-12-04 19:07:15
【问题描述】:
我正在使用 React Native 开发一个 Android 应用程序。我正在 Galaxy Nexus API 23 上测试我的应用程序,该应用程序正在 Android Studio 中模拟,在 Mac 上运行。
我希望允许用户彼此共享信息。我正在运行一个带有 php 和 mysql 的网络服务器,我希望该应用程序向服务器发出请求以在用户之间共享数据。
我正在尝试使用 Fetch API 向我的开发服务器发出 POST 请求。我的js代码如下:
var AjaxEngine = {
test: function() {
return fetch('http://10.0.2.2/test.json')
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
return responseJson.movies;
})
.catch((error) => {
console.error(error);
});
}
};
由AjaxEngine.test();调用
在我的模拟器中,我收到以下错误:
ExceptionsManager.js:70 TypeError: 网络请求失败 在 XMLHttpRequest.xhr.onerror (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:23711:8) 在 XMLHttpRequest.dispatchEvent (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:9740:15) 在 XMLHttpRequest.setReadyState (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:25157:6) 在 XMLHttpRequest.__didCompleteResponse (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:25015:6) 在http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:25090:52 在 RCTDeviceEventEmitter.emit (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:8977:23) 在 MessageQueue.__callFunction (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:7065:23) 在http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:6969:8 守卫 (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:6917:1) 在 MessageQueue.callFunctionReturnFlushedQueue (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:6968:1)
test.json 包括:
{
"message":"hello world"
}
我把'http://10.0.2.2/test.json'替换成'http://facebook.github.io/react-native/movies.json'时请求成功,所以函数本身就ok了。
'http://localhost/test.json' 和 'http://127.0.0.1/test.json' 都在 Web 浏览器中加载,curl 和 wget。我也试过用 127.0.0.1 替换 10.0.2.2。我也尝试过使用我的本地 ip (129.xxx.x.x)
我需要做什么才能使这些请求生效?如何从模拟的 android 应用访问在 localhost 上运行的开发服务器?
【问题讨论】:
标签: android ajax android-emulator react-native fetch-api