react native TypeError network request failed

image 

 

如果使用fetch获取数据,用的是POST方法,注意headers要添加请求头。当请求为GET时不能用body,当为POST时必须包含body,设置头部之后就一切正常了。

 

fetch("http://xx.xx.xx.xx/login.do?srt=2", {
    method : 'POST',
    body : JSON.stringify({
        SLoginCode : this.state.userName,
        SPasswd : this.state.userPwd,
        randCode : this.state.vertifyCode,
        m : 'login',
        language : 'cn',
        srt : '2'
    }),
    headers : {
        'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;',
        'Content-Type' : 'text/plain;charset=UTF-8',
        'User-Agent' : 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.89 Safari/537.36',
        'Host' : 'domain.xx.com',
    }
})
.then((response) => {
    console.log(response);
})
.catch((error) => {
    console.warn(error);
})
.done();

我在写一个工具的时候,发现自己把自己坑掉了。PC上怎么请求都正常,但是查看日志,包括在浏览器上Debug JS都发现返回的是tomcat 404错误的信息,我郁闷了很久,最后发现是PC上配置了host。而我直接请求时,手机上没有配置host,公网没有那个域名的请求,导致请求找不到。之后我改成直接通过ip请求,在头部中加上Host信息,这样就可以了。

 

官网也可以查到:https://facebook.github.io/react-native/docs/network.html#fetch

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值