簡體   English   中英

在Android上反應Native,使用fetch的ajax調用失敗

[英]React Native on Android, ajax call with fetch fails

我正在使用React Native開發Android應用程序。 我正在使用在Mac上運行的Android Studio中模擬的Galaxy Nexus API 23上測試我的應用。

我希望允許用戶彼此共享信息。 我正在運行一個帶有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();調用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 =真熱=假縮小=假:25157:6 )在XMLHttpRequest的.__ didCompleteResponse( HTTP://本地主機:8081 / index.android.bundle平台=機器人&dev的=真熱=假縮小=假:25015:6 )在HTTP://本地主機: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://本地主機:8081 / index.android.bundle平台=機器人&dev的=真熱=假縮小=假:7065:23 )在HTTP://本地主機 :8081 / index.android.bundle?platform = android&dev = true&hot = false&minify = false:6969:8 at guard( 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://facebook.github.io/react-native/movies.json'替換'http://10.0.2.2/test.json'時請求成功,所以函數本身沒問題。

'http://localhost/test.json''http://127.0.0.1/test.json'都加載到Web瀏覽器, curlwget 我也嘗試用127.0.0.1替換10.0.2.2。 我也試過使用我的本地ip(129.xxx.xx)

要使這些請求有效,我需要做什么? 如何從模擬的Android應用程序訪問在localhost上運行的開發服務器?

如果讓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. 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM