ES6 fetch函數與后台交互


最近在學習react-native,遇到調用后端接口的問題.看了看官方文檔,推薦使用es6的fetch來與后端進行交互,在網上找了一些資料.在這里整理,方便以后查詢.

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中的數據就是我們需要向服務器提交的數據,比如用戶名,密碼等;如果上述body中的數據提交失敗,那么你可能需要把數據轉換成如下的表單提交的格式:

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)
})
這樣可以獲取純文本的返回數據.
如果你需要返回json格式的數據:
fetch('
https://mywebsite.com/endpoint/').then(function(res) {

    if (res.ok) {

        res.json().then(function(obj) {

            // 這樣數據就轉換成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
 
 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM