欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時(shí)間:2017年12月02日 10:23:00   作者:Vonkin  
本篇文章主要介紹了React Native 使用Fetch發(fā)送網(wǎng)絡(luò)請(qǐng)求的示例代碼,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

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

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

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

GET

如果你想要通過 GET 方法去請(qǐng)求數(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);
   });

通過上面的請(qǐng)求把返回的 Response 轉(zhuǎn)化成 JSON Object,然后取出 JSON Object 里的 movies 字段。同時(shí),如果發(fā)生 Error,如網(wǎng)絡(luò)不通或訪問連接錯(cuò)誤等, 會(huì)被 .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 請(qǐng)求,F(xiàn)etch還有可選的第二個(gè)參數(shù),可以用來定制HTTP請(qǐng)求一些參數(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)建了一個(gè)基本的 POST 請(qǐng)求,添加了自己的 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請(qǐng)求,當(dāng)然這種方式也是被推薦使用的。

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

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

// `首先我們需要自己創(chuàng)建一個(gè)FormData,來存請(qǐng)求參數(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')
})

推薦這種方法的好處還有一個(gè),就是可以在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ā)起請(qǐng)求。很多情況下,你還需要處理服務(wù)器回復(fù)的數(shù)據(jù)。
網(wǎng)絡(luò)請(qǐng)求天然是一種異步操作,F(xiàn)etch 方法會(huì)返回一個(gè)Promise,這種模式可以簡(jiǎn)化異步風(fēng)格的代碼,關(guān)于Promise,請(qǐng)參考:Promise

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

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

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論