最近在學(xué)習(xí)react-native,遇到調(diào)用后端接口的問題.看了看官方文檔,推薦使用es6的fetch來與后端進行交互,在網(wǎng)上找了一些資料.在這里整理,方便以后查詢.
1.RN官方文檔中,可使用XMLHttpRequest
var request = new XMLHttpRequest();request.onreadystatechange = (e) = >{  if (request.readyState !== 4) {    return;  }  if (request.status === 200) {    console.log('success', request.responseText);  } else {    console.warn('error');  }};request.open('GET', 'https://mywebsite.com/endpoint.php');request.send();這是http的原生方法,這里不做多的介紹.
2.RN官方文檔中,推薦使用fetch
fetch('https://mywebsite.com/endpoint/', {  method: 'POST',  headers: {    'Accept': 'application/json',    'Content-Type': 'application/json',  },  body: JSON.stringify({    firstParam: 'yourValue',    secondParam: 'yourOtherValue',  })}).then(function(res) {  console.log(res)})body中的數(shù)據(jù)就是我們需要向服務(wù)器提交的數(shù)據(jù),比如用戶名,密碼等;如果上述body中的數(shù)據(jù)提交失敗,那么你可能需要把數(shù)據(jù)轉(zhuǎn)換成如下的表單提交的格式:
fetch('https://mywebsite.com/endpoint/', {  method: 'POST',  headers: {    'Content-Type': 'application/x-www-form-urlencoded',  },  body: 'key1=value1&key2=value2'}).then(function(res) {    console.log(res)})這樣可以獲取純文本的返回數(shù)據(jù).
如果你需要返回json格式的數(shù)據(jù):
fetch('https://mywebsite.com/endpoint/').then(function(res) {  if (res.ok) {    res.json().then(function(obj) {      // 這樣數(shù)據(jù)就轉(zhuǎn)換成json格式的了    })  }}, function(ex) {  console.log(ex)})fetch模擬表單提交:
fetch('doAct.action', {   method: 'post',   headers: {    "Content-type": "application/x-www-form-urlencoded; charset=UTF-8"   },   body: 'foo=bar&lorem=ipsum'  }) .then(json)  .then(function (data) {   console.log('Request succeeded with JSON response', data);  })  .catch(function (error) {   console.log('Request failed', error);  });不過無論是ajax還是fetch,都是對http進行了一次封裝,大家各取所好吧.
參考文檔:https://developer.mozilla.org/zh-CN/docs/Web/API/GlobalFetch/fetch
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持VeVb武林網(wǎng)。
新聞熱點
疑難解答