react native TypeError network request failed

如果使用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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章