溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

React Native 使用Fetch發(fā)送網(wǎng)絡(luò)請求的示例代碼

發(fā)布時(shí)間:2020-08-24 07:48:39 來源:腳本之家 閱讀:182 作者:Vonkin 欄目:web開發(fā)

我們在項(xiàng)目中經(jīng)常會用到HTTP請求來訪問網(wǎng)絡(luò),HTTP(HTTPS)請求通常分為"GET"、"PUT"、"POST"、"DELETE",如果不指定默認(rèn)為GET請求。

在項(xiàng)目中我們常用到的一般為GET和POST兩種請求方式,針對帶參數(shù)的表單提交這類的請求,我們通常會使用POST的請求方式。

為了發(fā)出HTTP請求,我們需要使用到 React Native 提供的 Fetch API 來進(jìn)行實(shí)現(xiàn)。要從任意地址獲取內(nèi)容的話,只需簡單地將網(wǎng)址作為參數(shù)傳遞給fetch方法即可(fetch這個詞本身也就是獲取的意思

GET

如果你想要通過 GET 方法去請求數(shù)據(jù)并轉(zhuǎn)化成 JSON,可以通過如下代碼實(shí)現(xiàn):

fetch('https://facebook.github.io/react-native/movies.json')
   .then((response) => response.json())
   .then((responseJson) => {
    return responseJson.movies;
   })
   .catch((error) => {
    console.error(error);
   });

通過上面的請求把返回的 Response 轉(zhuǎn)化成 JSON Object,然后取出 JSON Object 里的 movies 字段。同時(shí),如果發(fā)生 Error,如網(wǎng)絡(luò)不通或訪問連接錯誤等, 會被 .catch 。在正常的情況下,我們可以得到如下結(jié)果:

{
 "title": "The Basics - Networking",
 "description": "Your app fetched this from a remote endpoint!",
 "movies": [
  { "title": "Star Wars", "releaseYear": "1977"},
  { "title": "Back to the Future", "releaseYear": "1985"},
  { "title": "The Matrix", "releaseYear": "1999"},
  { "title": "Inception", "releaseYear": "2010"},
  { "title": "Interstellar", "releaseYear": "2014"}
 ]
}

POST(一)

當(dāng)然,上面是最基本的 GET 請求,F(xiàn)etch還有可選的第二個參數(shù),可以用來定制HTTP請求一些參數(shù)。你可以指定Headers參數(shù),或是指定使用POST方法,又或是提交數(shù)據(jù)等等:Fetch API 還支持自定義 Headers,更換 Method,添加 Body 等。

let url = "http://www.yousite.com/xxxx.ashx” 
let params = {"name":"admin","password":"admin"}; 
fetch(url, {
 method: 'POST',
 headers: {
  'Accept': 'application/json',
  'Content-Type': 'application/json',
 },
 body: JSON.stringify(params)
})

上面構(gòu)建了一個基本的 POST 請求,添加了自己的 Headers:Accept和Content-Type,添加了 Body。

POST(二)

let url = "http://www.yousite.com/xxxx.ashx”; 
let params = "username=admin&password=admin”; 
fetch(url, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  },
  body: params,
}).then((response) => {
  if (response.ok) {
    return response.json();
  }
}).then((json) => {
  console.log(json)
}).catch((error) => {
  console.error(error);
});

POST(三)推薦

通過上面兩種方法,我們還有一種方式可以發(fā)送POST請求,當(dāng)然這種方式也是被推薦使用的。

如果你的服務(wù)器無法識別上面POST的數(shù)據(jù)格式,那么可以嘗試傳統(tǒng)的form格式,示例如下:

let REQUEST_URL = 'http://www.yousite.com/xxxx.ashx';

// `首先我們需要自己創(chuàng)建一個FormData,來存請求參數(shù)`

let parameters = new FormData();
parameters.append("mt", "30013");
parameters.append("pg", "1");
parameters.append('ps', '20');


fetch(REQUEST_URL, {
  method: 'POST',
  body: parameters
}).then(
  (result) => {
    if (result.ok) {
      console.log(result)
      result.json().then(
        (obj) => {
          console.log(obj)
        }
      )
    }
  }
).catch((error) => {
  console.log(error)
  Alert.alert('Error')
})

推薦這種方法的好處還有一個,就是可以在FormData中直接傳遞字節(jié)流實(shí)現(xiàn)上傳圖片的功能,代碼如下:

uploadImage(){ 
 let formData = new FormData(); 
 let file = {uri: uri, type: 'multipart/form-data', name: 'a.jpg'}; 

 formData.append("images",file); 

 fetch(url,{ 
  method:'POST', 
  headers:{ 
    'Content-Type':'multipart/form-data', 
  }, 
  body:formData, 
 }) 
 .then((response) => response.text() ) 
 .then((responseData)=>{ 

  console.log('responseData',responseData); 
 }) 
 .catch((error)=>{console.error('error',error)}); 

}


處理服務(wù)器的響應(yīng)數(shù)據(jù)

上面的例子演示了如何發(fā)起請求。很多情況下,你還需要處理服務(wù)器回復(fù)的數(shù)據(jù)。
網(wǎng)絡(luò)請求天然是一種異步操作,F(xiàn)etch 方法會返回一個Promise,這種模式可以簡化異步風(fēng)格的代碼,關(guān)于Promise,請參考:Promise

處理服務(wù)器返回的數(shù)據(jù),我們已經(jīng)在上面第二種和第三種的POST請求中實(shí)現(xiàn)了數(shù)據(jù)的處理。具體代碼參考上面的實(shí)現(xiàn)代碼。

默認(rèn)情況下,iOS會阻止所有非https的請求。如果你請求的接口是http協(xié)議,那么首先需要添加一個App Transport Security的例外。

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI