我正在開發一個使用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:網絡請求失敗(...)。
如何使這項工作?
謝謝!有效。 – Chetan
我打電話給網址,但仍然有相同的錯誤。 fetch('http://private-18642-test2979.apiary-mock.com/notes/1',{ 方法:'get', 'headers':{ 'Accept':'application/json' , } –
這不是一個真正的URL,你也需要添加協議。 – oblador