React Native:fetch request failed with error - TypeError:网络请求失败(...) [英] React Native: fetch request failed with error - TypeError: Network request failed(…)

查看:1485
本文介绍了React Native:fetch request failed with error - TypeError:网络请求失败(...)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用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 for for /');
res.send(这是从服务器);
res.end();
});

但是,提取请求无效。在Chrome控制台中出现的错误是:
TypeError:网络请求失败(...)。



如何使这项工作?

解决方案

由于您的Android设备具有自己的IP,因此您需要将URL指向您的计算机IP地址而不是本地主机。例如 fetch('http://192.168.0.2:3333/')


I am developing a simple app using React Native. I am testing it on Android device. I have created a Node.js server to listen to the requests, it is running at http://localhost:3333/. Next, I am making a fetch request from index.android.js. Below is the code.

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

The code for the request handler at node server is below

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();
});

But, the fetch request is not working. The error I get in the Chrome console is: TypeError: Network request failed(…).

How to make this work?

解决方案

Since your Android device has an IP of its own, you need to point the URL to your computers IP address instead of just localhost. For example fetch('http://192.168.0.2:3333/').

这篇关于React Native:fetch request failed with error - TypeError:网络请求失败(...)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆