2015-11-28 156 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,因此您需要將URL指向您的計算機IP地址而不是本地主機。例如fetch('http://192.168.0.2:3333/')

+0

謝謝!有效。 – Chetan

+0

我打電話給網址,但仍然有相同的錯誤。 fetch('http://private-18642-test2979.apiary-mock.com/notes/1',{ 方法:'get', 'headers':{ 'Accept':'application/json' , } –

+0

這不是一個真正的URL,你也需要添加協議。 – oblador

10

中使用Android調試橋工具(ADB)的反向命令:

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> 

例如:

adb reverse tcp:3333 tcp:3333 

這使得localhost:3333從您的設備訪問。您也可以使用不同的端口。例如:

adb reverse tcp:8081 tcp:3333 

這將設備端口8081重定向到服務端口3333