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