![](/img/trans.png)
[英]React native TypeError: Network request failed with fetch()
[英]React Native: fetch request failed with error - TypeError: Network request failed(…)
我正在使用React Native開發一個簡單的應用程序。 我在Android設備上測試它。 我創建了一個Node.js服務器來監聽請求,它運行在http:// localhost:3333 / 。 接下來,我正在從index.android.js發出一個獲取請求。 下面是代碼。
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:網絡請求失敗(...)。
如何使這項工作?
由於您的Android設備具有自己的IP,因此您需要將URL指向您的計算機IP地址,而不僅僅是localhost。 例如fetch('http://192.168.0.2:3333/')
。
使用Android Debug Bridge工具(adb)的reverse命令:
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。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.