2016-07-30 10 views
6

Я разрабатываю Android-приложение с помощью React Native. Я тестирую свое приложение на Galaxy Nexus API 23, которое эмулируется в Android Studio, работающем на Mac.React Native на Android, вызов ajax с извлечением извлечения

Я хочу, чтобы пользователи могли обмениваться информацией друг с другом. Я запускаю веб-сервер с php и mysql, и я хочу, чтобы приложение делало запросы на сервер для обмена данными между пользователями.

Я пытаюсь сделать запрос POST для моего сервера разработки с помощью API-интерфейса Fetch. Мой 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: Network request failed at XMLHttpRequest.xhr.onerror (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:23711:8) at XMLHttpRequest.dispatchEvent (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:9740:15) at XMLHttpRequest.setReadyState (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:25157:6) at XMLHttpRequest.__didCompleteResponse (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:25015:6) at http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:25090:52 at RCTDeviceEventEmitter.emit (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:8977:23) at MessageQueue.__callFunction (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:7065:23) at http://localhost: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) at 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' как нагрузки в веб-браузере, curl и wget. Я также попытался заменить 10.0.2.2 на 127.0.0.1. Я также пробовал использовать мой местный ip (129.xxx.x.x)

Что мне нужно сделать, чтобы эти запросы работали? Как получить доступ к моему серверу разработки, работающему на локальном хосте, из эмулированного приложения для Android?

ответ

0

Если у вас есть завиток, попробуйте параметр -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.