在Android上反应Native,使用fetch的ajax调用失败

时间:2016-07-30 01:07:07

标签: android ajax android-emulator react-native fetch-api

我正在使用React Native开发Android应用。我正在使用在Android上模拟的Galaxy Nexus API 23上测试我的应用程序,在Mac上运行。

我希望允许用户相互分享信息。我正在运行一个带有php和mysql的web服务器,我希望应用程序向服务器发出请求,以便在用户之间共享数据。

我正在尝试使用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'时请求成功,因此该功能本身就可以。

'http://localhost/test.json''http://127.0.0.1/test.json'都会加入网络浏览器curlwget。我也尝试用127.0.0.1替换10.0.2.2。我也尝试过使用我的本地ip(129.xxx.x.x)

要使这些请求有效,我需要做什么?如何从模拟的Android应用程序访问在localhost上运行的开发服务器?

1 个答案:

答案 0 :(得分:0)

如果让curl工作,请尝试-D选项,该选项将标头写入文件。这样,你可以看到两个请求是否都有f.ex.相同的哑剧类型。

   -D, --dump-header <file>
          Write the protocol headers to the specified file.

          This option is handy to use when you want to store  the  headers
          that  an  HTTP site sends to you. Cookies from the headers could
          then be read in a  second  curl  invocation  by  using  the  -b,
          --cookie  option! The -c, --cookie-jar option is a better way to
          store cookies.