2015-11-28 24 views
15

React Nativeを使用して簡単なアプリケーションを開発しています。私はAndroidのデバイスでそれをテストしています。私は、要求を聞くためにNode.jsサーバーを作成しました。それはhttp://localhost:3333/で実行されています。 次に、index.android.jsからフェッチ要求を出しています。以下はコードです。React Native:フェッチ要求がエラーで失敗しました - TypeError:ネットワーク要求が失敗しました(...)

fetch('http://localhost:3333/', 
     { 
      'method': 'GET', 
      'headers': { 
       'Accept': 'text/plain',          
      } 
     }  
    ) 
.then((response) => response.text()) 
.then((responseText) => { 
    console.log(responseText); 
}) 
.catch((error) => { 
    console.warn(error); 
}); 

ノードサーバの要求ハンドラのコードは、フェッチ要求が動作していない、以下

app.use(function(req, res, next) { 
    res.header("Access-Control-Allow-Origin", "*"); 
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); 
    next(); 
}); 
app.use(express.static('public')); 
app.get('/', function(req, res){ 
    console.log('Request received for /'); 
    res.send("this is the response from the server"); 
    res.end(); 
}); 

ですが。 Chromeコンソールに表示されるエラーは次のとおりです。 TypeError:ネットワークリクエストが失敗しました(...)。

この作品を作成するには?

答えて

27

あなたのAndroidデバイスは独自のIPアドレスを持っているので、localhostの代わりにコンピュータのIPアドレスを指定する必要があります。たとえば、fetch('http://192.168.0.2:3333/')です。例えば

adb reverse <remote> <local> - reverse socket connections. 
           reverse specs are one of: 
           tcp:<port> 
           localabstract:<unix domain socket name> 
           localreserved:<unix domain socket name> 
           localfilesystem:<unix domain socket name> 

+0

感謝をデバイスポート8081をリダイレクトします!出来た。 – Chetan

+0

私はurlを呼び出していますが、同じエラーが表示されています。 fetch( 'http://private-18642-test2979.apiary-mock.com/notes/1'、{ メソッド: 'get'、 'ヘッダー':{ 'Accept': 'application/json' 、 } –

+0

これは実際にはURLではないので、プロトコルも追加する必要があります。 – oblador

10

は、Androidデバッグブリッジツール(ADB)のコマンドを使用します

adb reverse tcp:3333 tcp:3333 

これは、お使いのデバイスからlocalhost:3333にアクセスできるようになります。異なるポートを使用することもできます。たとえば:

adb reverse tcp:8081 tcp:3333 

これは、サービスポートに3333

関連する問題